1

I am trying to create a update function in order to update student marks value in the same csv file when the or studentID matches that is queried by the user; My csv file looks like following;

Name, studentID, Marks, Grade
Joan,   1735,   90,    A
Dev,    0374,   69,    B
Betty,  647,    55,    C

My tried code is:

def updatefunc():
stid= input("Enter a studentID : ")
fieldnames = ["Name", "StuID", 'Marks', 'Grade']
with open('File.csv', 'r') as csvfile, open('output.csv', 'w') as output:
    reader = csv.DictReader(csvfile, fieldnames=fieldnames)
    writer = csv.DictWriter(output, fieldnames=fieldnames)
    for row in reader:
        if chid == row['ID']:
            row['Marks'] = input("enter new name  {}".format(Marks))
        
        writer.writerow({'Name': row['Name'], 'StuID': row['StuID'], 'Marks': row['Marks'],'Grade': row['Grade']})
snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
Ddevil Prasad
  • 117
  • 1
  • 14
  • Does this help? https://stackoverflow.com/questions/64183776/i-want-to-delete-rows-from-line-2-to-a-specific-numbers-in-csv-file-but-it-dele – snakecharmerb Oct 04 '20 at 16:51
  • the answer in the thread using two files but I need to save the updated row in the same file. – Ddevil Prasad Oct 04 '20 at 16:55
  • You could take a look at [this answer](https://stackoverflow.com/a/64190704/5320906). You either need to follow that example - write to a temporary file then rename, or read the file into memory and update the data, close it and then reopen in write mode and write out the data. – snakecharmerb Oct 04 '20 at 17:01
  • I just wanted to use the csv package...there are other two packages..isn't it possible to do it using only csv package? – Ddevil Prasad Oct 04 '20 at 17:09

1 Answers1

1

If you are constrained to using only the csv module, you need to:

  • read the file
  • save all the rows to a new list, updated as necessary
  • write the data out to a new file
def updatefunc():
    new_rows = []
    stid= input("Enter a studentID : ")
    fieldnames = ["Name", "StuID", 'Marks', 'Grade']
    with open('File.csv', 'r') as csvfile:
        reader = csv.DictReader(csvfile, fieldnames=fieldnames)
        for row in reader:
            if stid == row['StuID']:
                row['Marks'] = input("enter new name  {}".format(Marks))
            new_rows.append({'Name': row['Name'], 'StuID': row['StuID'], 'Marks': row['Marks'],'Grade': row['Grade']})

    # Write the amended data out to the file.
    with open('File.csv', 'w') as output:
        writer = csv.DictWriter(output, fieldnames=fieldnames)
        writer.writerows(new_rows)
snakecharmerb
  • 47,570
  • 11
  • 100
  • 153