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

Time:07-08

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.

CodePudding user response:

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.

  • Related