使用读/写同一文件csv.dictreaderpython

2024-09-30 18:20:35 发布

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

我有以下代码,它接受一个csv文件,并且只删除与fields列表匹配的列。在

def mi_columnDeleter(filenameWithPath):
    #The fields I want
    fields = ["Part Number", "Full MI", "Accepts", "Attempts"]

    #Open the file
    infile = codecs.open(filenameWithPath, 'rb')    
    #hook the DictReader
    r = csv.DictReader(infile)
    #error occurs here because I have it before 'r' below
    infile.close()
    #open the same file
    outfile = open(filenameWithPath, "wb")
    w = csv.DictWriter(outfile, fields, extrasaction="ignore")
    w.writeheader()
    for row in r:
        w.writerow(row)
    outfile.close()

我得到以下I/O错误I/O operation on closed file,因为在使用r之前,我有{}。在

我的问题是,有没有一种方法可以读入csv数据-将其剪切到正确的列中-然后将其保存回同一个文件中?在

我知道有一些变通方法,但我确信python应该能够做到这一点。在


Tags: 文件csvthe代码fields列表closedef
1条回答
网友
1楼 · 发布于 2024-09-30 18:20:35

如果要重新打开同一个文件进行写入,需要先将行存储在列表中,则不能先关闭文件,然后再尝试遍历以下行:

 r = csv.DictReader(infile)
 r = list(r)
 ..........

更好的方法是写入tempfile,在更新后使用shutil.move替换原始文件:

^{pr2}$

用作输入:

a,b,c
1,2,3
4,5,6

定义为fields = ["a","c"]的字段将输出:

a,c
1,3
4,6

您也可以简单地调用writerows传入reader对象,并在自己的代码中使用for循环。在

相关问题 更多 >