【问题标题】:I keep getting "ValueError: I/O operation on closed file" error message when i am trying to write to a file in python当我尝试在 python 中写入文件时,我不断收到“ValueError: I/O operation on closed file”错误消息
【发布时间】:2021-01-31 00:46:39
【问题描述】:
def writeToFile(self):
 file= open("C:\\Users\\Gabri\\Pictures\\newInternationalCases.csv", "w", newline='')
 with file:
  write = csv.writer(file);
 write.writerow(self.recordList);

这是上面的代码,我的目的是让它创建文件并写入它。 “recordList”是我要写入文件的二维列表

【问题讨论】:

    标签: python python-3.x python-2.7 file


    【解决方案1】:
    path = r"C:\Users\Gabri\Pictures\newInternationalCases.csv"
    with open(path, 'w', newline='') as file:
        write = csv.writer(file)
        write.writerow(self.recordList) 
    

    【讨论】:

      【解决方案2】:

      with file在块的末尾关闭文件,所以你只能在with里面写。

      with file:
          write = csv.writer(file)
          # Inside 'with' block
          write.writerow(self.recordList)
      

      还要注意,将open 放在with 的顶部是很正常的:

      path = r"C:\Users\Gabri\Pictures\newInternationalCases.csv"
      with open(path, 'w', newline='') as file:
          write = csv.writer(file)
          write.writerow(self.recordList)
      

      【讨论】:

      • 所以如果我在 with 块中缩进它应该可以工作吗?
      • 是的,您应该将其缩进到 with 块内。
      猜你喜欢
      • 2015-11-27
      • 2021-11-17
      • 2018-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-02
      • 2022-11-25
      相关资源
      最近更新 更多