python - 值错误 : I/O operation on closed file even after giving second arg for open()

标签 python excel xlrd xlsxwriter

我正在尝试运行这段代码:

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 block 将为您关闭文件。只需删除您的显式关闭即可。

关于python - 值错误 : I/O operation on closed file even after giving second arg for open(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44072457/

相关文章:

python - 将 Excel 文件文件夹转换为 CSV 文件/合并 Excel 工作簿

python - 为什么运行此脚本时得到 "OSError: [Errno 2] No such file or directory"?

python - 输入形状的卷积神经网络错误

excel - 在Excel工作表中存储对象?

python - 如何以不同的对齐方式将QLabels添加到QTableWidget中

excel - 是否有任何 REST API 用于在 OneDrive 云中创建新的 Excel (.xlsx) 文件

Excel VBA 创建文件夹、子文件夹和其他子文件夹

python - 使用 xlrd 在 Python 3 中将 xls 转换为 csv

python - 如何为普通 pgm 格式编写 PIL 图像过滤器?

Python "in"和 "=="混淆