ValueError: I/O operation on closed file even after giving second arg for open()

ValueError: I/O operation on closed file even after giving second arg for open()

我正在尝试 运行 此代码:

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()

但是当我 运行 它时,我得到以下错误:

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.

使用 with 您实际上不需要关闭文件。

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 common try...except...finally usage patterns to be encapsulated for convenient reuse.

此处隐藏的隐式 finally 块将为您关闭文件。只需删除您的显式关闭即可。