Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

python - How to update rows in a CSV file

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...