ValueError: I / O operation on closed file even after providing second argument to open ()

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.

      

+3


source to share


1 answer


With, with

you really don't need to close the file.

The operator is with

used to wrap the execution of a block using methods defined by the context manager (see the section With Expression, Context Managers ). This allows for common try...except...finally

templates to be encapsulated for easy reuse.



The implicit finally block, which is hidden here, will close the file for you. Just remove your explicit closure and you should be fine.

+2


source







All Articles