如何更新CSV文件中的行 [英] How to update rows in a CSV file

查看:166
本文介绍了如何更新CSV文件中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在尝试制作一个更新csv中值的程序.用户搜索ID,如果ID存在,它将在该ID号所在的行上获取要替换的新值. row[0:9]是我的ID的长度.

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.

我的想法是从0-9扫描每行或我的ID编号在哪里,当找到它时,我将使用.replace()方法替换它旁边的值.这是我的方法:

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.

推荐答案

使用csv模块,您可以遍历行并将每个行作为dict进行访问.还如此处所述,更新文件的首选方法是使用临时文件.

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:

添加了str,打印和编码

added str, print and encodings

这篇关于如何更新CSV文件中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆