如何更新CSV fi中的行

2024-05-08 14:34:14 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,我正在尝试制作一个程序,更新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()  

但这不管用,我需要一些解决办法。

Screenshot


Tags: csv用户程序idcloseifopenfilename
2条回答

使用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、打印和编码

只需在读取原始行的同时写入一个新文件,根据Stud\u 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)

相关问题 更多 >

    热门问题