0

I'm trying to read a database file to check if it matches the csv file. If it is inside the database but not in the csv file, I want to write the Student number and the status which is absent. Is there a better way to code this since it requires both reading and writing of a csv file?

def absents(cutoff, batch, dates):
    with open(batch+"-"+dates+".csv", "r") as file:
        reader = csv.DictReader(file)

        for row in reader:
            studentr = ""
            counter = 0
            if counter != 1:
                with open(batch+"-"+dates+".csv", "a") as file:
                    fnames = ['Student_Number', 'Datetime', 'Status']
                    writer = csv.DictWriter(file, fieldnames=fnames)
                    writer.writerow(
                        {'Student_Number': studentr, 'Datetime': None, 'Status': "absent"})
                    counter = 0
            for i in range(200000, 200100):
                student = db.execute("SELECT * FROM Student WHERE id_number = :i", i=i)
                studentnumber = row["Student_Number"]
                if student[0]["id_number"] == studentnumber:
                    studentr = student[0]["id_number"]
                    counter = 1
    return options_mode(cutoff, batch, dates)
martineau
  • 119,623
  • 25
  • 170
  • 301
  • Shouldn't the logic of querying the db go before the check `if counter != 1`? Else, counter is always 0, and the `if` statement is redundant. – ghost Jul 04 '20 at 08:54
  • I think this might help you solve the problem: [Open it with either a+ or r+](https://stackoverflow.com/questions/56381066/how-to-open-file-in-read-and-append-mode-in-python-at-the-same-time-in-one-varia). With this, you can both read and write with just one `with` statement – Michael Teguh Laksana Jul 04 '20 at 08:56
  • 1
    Does this answer your question? [read and write on same csv file](https://stackoverflow.com/questions/3146571/read-and-write-on-same-csv-file) – ghost Jul 04 '20 at 08:58
  • 1
    No. You cannot modify (write to) the csv file you're reading while doing so. – martineau Jul 04 '20 at 09:33
  • What I did is I split the function into two so there is a read and whatever it read will be stored in a list then close then open again the append. – Aladin Oliver Yu Jul 04 '20 at 13:28

0 Answers0