Zedak
Zedak

Reputation: 289

Trouble in writing a pandas Dataframe to excel file

I have a list of excel files, I am creating dataframes from them. I perform few tasks on the dataframes and then try to write these dataframes back into the file(more like replacing them entirely). But I am unable to write the files.

Here is the code

for file in files:
    file_name = os.path.basename(file)
    table = pd.read_excel(file, 0)
    ## (Perform Operations here)          
    writer = pd.ExcelWriter(file)
    df.to_excel(writer,'Sheet1')
    writer.save

Now when I try to read the file back into pandas I am getting this error

FileNotFoundError: [Errno 2] No such file or directory: 'test2.xlsx'

There are no files being created anywhere. But I am unable to tell where am I going wrong. Also writer.save returns

<bound method _XlsxWriter.save of <pandas.io.excel._XlsxWriter object at 0x000000000B9712E8>>

Upvotes: 1

Views: 3921

Answers (1)

Abdou
Abdou

Reputation: 13294

The issue is that you are calling write.save without the parentheses. This would have worked if .save was just an attribute. But since it is a method, it needs to be called with the parentheses for any effect to occur. Therefore, you should change your code to the following:

for file in files:
    file_name = os.path.basename(file)
    table = pd.read_excel(file, 0)
    ## (Perform Operations here)          
    writer = pd.ExcelWriter(file)
    df.to_excel(writer,'Sheet1')
    writer.save()

I hope this helps.

Upvotes: 2

Related Questions