I am trying to run this code:
我正在尝试运行此代码:
import xlrd
import os.path
import xlsxwriter
with open("arrays.xlsx", "a") as my_file:
workbook = xlsxwriter.Workbook(my_file)
worksheet = workbook.add_worksheet()
array = [1, 2, 3, 4, 5]
row = 0
for col, data in enumerate(array):
worksheet.write_column(row, 0, array)
workbook.close()
But when I run it, I get the following error:
但是当我运行它时,我收到以下错误:
Traceback (most recent call last):
File "C:\Users\hp\Anaconda3\lib\zipfile.py", line 1649, in __del__
self.close()
File "C:\Users\hp\Anaconda3\lib\zipfile.py", line 1666, in close
self.fp.seek(self.start_dir)
ValueError: I/O operation on closed file.
1 个解决方案
#1
2
With with
you don't actually need to close the file.
与您一起实际上不需要关闭文件。
The
with
statement is used to wrap the execution of a block with methods defined by a context manager (see section With Statement Context Managers). This allows commontry...except...finally
usage patterns to be encapsulated for convenient reuse.with语句用于使用上下文管理器定义的方法包装块的执行(请参阅使用语句上下文管理器一节)。这允许常见的尝试...除了...最终使用模式被封装以便于重用。
The implicit finally block which is hidden here will close the file for you. Just remove your explicit close and you will be fine.
这里隐藏的隐式finally块将为您关闭文件。只需删除您的明确关闭,您就可以了。
#1
2
With with
you don't actually need to close the file.
与您一起实际上不需要关闭文件。
The
with
statement is used to wrap the execution of a block with methods defined by a context manager (see section With Statement Context Managers). This allows commontry...except...finally
usage patterns to be encapsulated for convenient reuse.with语句用于使用上下文管理器定义的方法包装块的执行(请参阅使用语句上下文管理器一节)。这允许常见的尝试...除了...最终使用模式被封装以便于重用。
The implicit finally block which is hidden here will close the file for you. Just remove your explicit close and you will be fine.
这里隐藏的隐式finally块将为您关闭文件。只需删除您的明确关闭,您就可以了。