I / O文件没有打开

时间:2014-10-13 15:02:59

标签: python csv io

我有这个csv文件dl.dropboxusercontent.com/s/tb4yc3lm3gg3j22/out.csv,我试图用下面的read方法替换最后一列。 在我的input.csv中,我必须用一些计算替换最后一个字段。我尝试如下,但不知何故,我得到ValueError:关闭文件上的I / O操作。你能帮我指出错误吗?当我试图打开输入文件并将包括新值的所有内容写入out.csv文件时,该文件最初不存在但应该在运行中构建。

def read():
    for file in os.listdir("./"):
        if file.endswith('.csv'):
            fNameFull = os.path.basename(file)
            inputFileName = os.path.splitext(file)[0]
            with open(fNameFull, "rb") as infile, open('out.csv', "wb") as outfile:
                r = csv.DictReader(infile)
                w = csv.DictWriter(outfile, r.fieldnames)
                w.writeheader()
                for row in r:
                    if not row["col_last"].strip():
                        row["col_last"] = "calc_value"
                    w.writerow(row)

if __name__ == '__main__':
    main()
    read()

错误:

Traceback (most recent call last):
  File "C:\Users\hp\Desktop\final\text\finalmod.py", line 50, in <module>
    read()
  File "C:\Users\hp\Desktop\final\text\finalmod.py", line 39, in read
    w.writeheader()
  File "C:\Python27\lib\csv.py", line 137, in writeheader
    self.writerow(header)
  File "C:\Python27\lib\csv.py", line 148, in writerow
    return self.writer.writerow(self._dict_to_list(rowdict))
ValueError: I/O operation on closed file

0 个答案:

没有答案