Python 如何更新 CSV 文件中的行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46126082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to update rows in a CSV file
提问by Jed Hart
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.
您好,我正在尝试制作一个程序来更新 csv 中的值。用户搜索 ID,如果 ID 存在,它会在该 ID 号所在的行上获取要替换的新值。这row[0:9]
是我的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:
我的想法是从 0-9 或我的 ID 号所在的位置扫描每一行,当找到时,我将使用该.replace()
方法替换它之外的值。我是这样做的:
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.
但它不起作用,我需要关于如何解决这个问题的想法。
回答by brennan
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.
使用该csv
模块,您可以遍历行并将每一行作为字典访问。正如这里还提到的,更新文件的首选方法是使用临时文件。
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
编辑:添加了 str、print 和 encodings
回答by Parfait
Simply write to a new file at same time reading over the lines of original, conditionally changing the row based on Stud_IDvalue. New file is suffixed _newin name.
只需在读取原始行的同时写入新文件,根据Stud_ID值有条件地更改行。新文件的名称后缀为_new。
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)