使用csv.dictreader python读/写同一文件

时间:2015-08-19 17:11:22

标签: python csv

我有以下代码,该代码采用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,因为在使用infile.close()之前我有r

我的问题是有没有办法读取csv数据 - 将其删除到正确的列 - 然后将其保存回同一个文件?

我知道有解决方法,但我确信python应该能够做到这一点。

1 个答案:

答案 0 :(得分:1)

如果你想重新打开同一个文件进行编写,你需要先将行存储在列表中,你不能关闭文件,然后尝试迭代这些行:

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

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

from shutil import move
from tempfile import NamedTemporaryFile
import csv
import os

def mi_columnDeleter(filenameWithPath):
    fields = ["Part Number", "Full MI", "Accepts", "Attempts"]
    with codecs.open(filenameWithPath, 'rb') as f, NamedTemporaryFile("w",dir=".", delete=False) as temp:
        r = csv.DictReader(f)
        w = csv.DictWriter(temp, fields, extrasaction="ignore")
        w.writeheader()
        w.writerows(r)
    move(temp.name,filenameWithPath)

用作输入:

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

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

a,c
1,3
4,6

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