Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

"ValueError: I/O operation on closed file" on saving multiple DataFrames in 1 excel file

I’m having an error output trying to save multiple DataFrames in a singles excel file.
Here’s my code:

import pandas as pd

path  = ['path1.txt', 'path2.txt', 'path3.txt']

data = []
data = [pd.read_csv(i, sep=" ") for i in path]
 
with pd.ExcelWriter("output.xlsx", engine="openpyxl") as writer:
    for i in range(len(data)):
        data[i].to_excel(writer, sheet_name= path[i].replace(".txt", ""), index=False)
    writer.save()
writer.close()

What I’m doing wrong? I’ve tried many solutions, but didn’t worked.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The context manager in the with clause closes the file when you exit the block. The additional explicit writer.close() call is redundant and causes this error. Remove it and you should be OK.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading