我有以下代码,它接受一个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应该能够做到这一点。在
如果要重新打开同一个文件进行写入,需要先将行存储在列表中,则不能先关闭文件,然后再尝试遍历以下行:
更好的方法是写入tempfile,在更新后使用shutil.move替换原始文件:
^{pr2}$用作输入:
定义为
fields = ["a","c"]
的字段将输出:您也可以简单地调用
writerows
传入reader对象,并在自己的代码中使用for循环。在相关问题 更多 >
编程相关推荐