Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update rows in a CSV file

Tags:

python

csv

Hello I'm trying to make a program that updates the values in a csv. The user searches for the ID, and if the ID exists, it gets the new values you want to replace on the row where that ID number is. Here row[0:9] is the length of my ID.

My idea was to scan each row from 0-9 or where my ID number is, and when its found, I will replace the values besides it using the .replace() method. This how i did it:

    def update_thing():
        replace = stud_ID +','+ stud_name +','+ stud_course +','+ stud_year
        empty = []
        with open(fileName, 'r+') as upFile:
            for row in f:
                if row[0:9] == stud_ID:
                    row=row.replace(row,replace)
                    msg = Label(upd_win, text="Updated Successful", font="fixedsys 12 bold").place(x=3,y=120)
                if not row[0:9] == getID:
                    empty.append(row)

        upFile.close()
        upFile = open(fileName, 'w')
        upFile.writelines(empty)
        upFile.close()  

But it's not working, I need ideas on how to get through this.

Screenshot

like image 794
Jed Hart Avatar asked Sep 09 '17 00:09

Jed Hart


People also ask

How do I change a CSV file value?

When working with a CSV file it is often necessary to find data contained within and sometimes replace it. Find & Replace is used for just this. You can access it from the Edit > Find & Replace menu or by pressing Ctrl-F on the keyboard.

How do I add data to an existing CSV file in Python?

If you need to append row(s) to a CSV file, replace the write mode ( w ) with append mode ( a ) and skip writing the column names as a row ( writer. writerow(column_name) ).


2 Answers

With the csv module you can iterate over the rows and access each one as a dict. As also noted here, the preferred way to update a file is by using temporary file.

from tempfile import NamedTemporaryFile
import shutil
import csv

filename = 'my.csv'
tempfile = NamedTemporaryFile(mode='w', delete=False)

fields = ['ID', 'Name', 'Course', 'Year']

with open(filename, 'r') as csvfile, tempfile:
    reader = csv.DictReader(csvfile, fieldnames=fields)
    writer = csv.DictWriter(tempfile, fieldnames=fields)
    for row in reader:
        if row['ID'] == str(stud_ID):
            print('updating row', row['ID'])
            row['Name'], row['Course'], row['Year'] = stud_name, stud_course, stud_year
        row = {'ID': row['ID'], 'Name': row['Name'], 'Course': row['Course'], 'Year': row['Year']}
        writer.writerow(row)

shutil.move(tempfile.name, filename)

If that's still not working you might try one of these encodings:

with open(filename, 'r', encoding='utf8') as csvfile, tempfile:
with open(filename, 'r', encoding='ascii') as csvfile, tempfile:

Edit: added str, print and encodings

like image 141
brennan Avatar answered Oct 09 '22 03:10

brennan


Simply write to a new file at same time reading over the lines of original, conditionally changing the row based on Stud_ID value. New file is suffixed _new in name.

line_replace = stud_ID +','+ stud_name +','+ stud_course +','+ stud_year

with open(fileName, 'r') as readFile, open(fileName.replace('.csv', '_new.csv'), 'w') as writeFile: 
   for row in readFile:
      if row[0:9] == stud_ID:
         writeFile.write(line_replace)
         msg = Label(upd_win, text="Updated Successful", font="fixedsys 12 bold").place(x=3,y=120)
      else: 
         writeFile.write(row)
like image 1
Parfait Avatar answered Oct 09 '22 03:10

Parfait