【问题标题】:ValueError : I/O operation on closed fileValueError : 对已关闭文件的 I/O 操作
【发布时间】:2013-09-27 23:07:39
【问题描述】:
import csv    

with open('v.csv', 'w') as csvfile:
    cwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)

for w, c in p.items():
    cwriter.writerow(w + c)

这里,p 是字典,wc 都是字符串。

当我尝试写入文件时,它会报告错误:

ValueError: I/O operation on closed file.

【问题讨论】:

    标签: python csv file-io io


    【解决方案1】:

    正确缩进;你的for 语句应该在with 块内:

    import csv    
    
    with open('v.csv', 'w') as csvfile:
        cwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)
    
        for w, c in p.items():
            cwriter.writerow(w + c)
    

    with 块之外,文件被关闭。

    >>> with open('/tmp/1', 'w') as f:
    ...     print(f.closed)
    ... 
    False
    >>> print(f.closed)
    True
    

    【讨论】:

      【解决方案2】:

      同样的错误可以通过混合引发:制表符+空格。

      with open('/foo', 'w') as f:
       (spaces OR  tab) print f       <-- success
       (spaces AND tab) print f       <-- fail
      

      【讨论】:

      • 是的,但是在 python 中混合它们时总是这样吗?
      【解决方案3】:
      file = open("filename.txt", newline='')
      for row in self.data:
          print(row)
      

      将数据保存到一个变量(file),所以你需要一个with

      【讨论】:

        【解决方案4】:

        另一个可能的原因是,在一轮 copypasta 之后,您最终读取了两个文件并为两个文件句柄分配了相同的名称,如下所示。注意嵌套的with open 语句。

        with open(file1, "a+") as f:
            # something...
            with open(file2, "a+", f):
                # now file2's handle is called f!
        
            # attempting to write to file1
            f.write("blah") # error!!
        

        然后解决方法是为两个文件句柄分配不同的变量名,例如f1f2 而不是 f

        【讨论】:

          【解决方案5】:

          我在 PyCharm 中调试时遇到了这个异常,因为没有遇到断点。为了防止它发生,我在 with 块之后添加了一个断点,然后它就停止了。

          【讨论】:

            【解决方案6】:

            当我在with open(...) as f: 中使用未定义的变量时,我遇到了这个问题。 我删除(或在外部定义)未定义的变量,问题就消失了。

            【讨论】:

              猜你喜欢
              • 2016-07-21
              • 2015-07-20
              • 1970-01-01
              • 1970-01-01
              • 2018-12-18
              • 2016-08-26
              • 2016-06-13
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多