您好我试图创建一个更新csv值的程序。用户搜索ID,如果ID存在,则会在ID号所在的行上获取要替换的新值。这里row[0:9]
是我的ID的长度。
我的想法是扫描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()
但是它不起作用,我需要有关如何解决这个问题的想法。
答案 0 :(得分:5)
使用csv
模块,您可以遍历行并将每个行作为dict访问。还注意到here,更新文件的优先方法是使用临时文件。
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)
如果仍然无法正常工作,您可以尝试其中一种编码:
with open(filename, 'r', encoding='utf8') as csvfile, tempfile:
with open(filename, 'r', encoding='ascii') as csvfile, tempfile:
编辑:添加了str,print和encodings
答案 1 :(得分:0)
只需同时写入新文件,读取原始行,根据 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)