当我试图用python编写文件时,我不断收到“ValueError:I/O operation on closed file”错误消息

2024-04-26 07:42:01 发布

您现在位置:Python中文网/ 问答频道 /正文

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

这是上面的代码,我的目的是让它创建文件并写入其中。“记录列表”是我想要写入文件的2D列表


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

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)

相关问题 更多 >