I am trying to use Pandas to write a dataframe to Excel. The data is just some price data from a public Crypto API:
My code is as follows:
writer = pd.ExcelWriter('crypto.xlsx')
btc.to_excel(writer, sheet_name='Bitcoin') # btc = dataframe
This code produces a corrupt .xlsx file. I have found that I can produce a working one if I add the following to the end of the code:
writer.save()
However, adding this line gives this warning:
C:\Users\UserName\AppData\Local\Temp\ipykernel_1504\1045303506.py:7: FutureWarning: save is not part of the public API, usage can give unexpected results and will be removed in a future version
writer.save()
What is the proper way to do this?
from the docs:
The writer should be used as a context manager. Otherwise, call
close()
to save and close any opened file handles.
So usually you will want to use with
(writer needs to know when writing is finished so it flushes everything to disk, and you might want to write multiple sheets for example):
with pd.ExcelWriter('crypto.xlsx') as writer:
btc.to_excel(writer, sheet_name='Bitcoin')
So you don't need to call close
manually (which is synonym for save
, to make it more file-like).
P.S.
save
is depricated.