Trying to save changes to the same xlsx file without overwriting it,
What I use to read the file
import pandas as pd file = 'path' df = pd.read_excel(f"{file}", 'sheet')
This has overwritten my file
df.to_excel(path)
According to Pandas team the following could be used
https://github.com/pandas-dev/pandas/blob/main/pandas/io/excel/_base.py#L800-L814
mode : {{'w', 'a'}}, default 'w' File mode to use (write or append). Append does not work with fsspec URLs. {storage_options} .. versionadded:: 1.2.0 if_sheet_exists : {{'error', 'new', 'replace', 'overlay'}}, default 'error' How to behave when trying to write to a sheet that already exists (append mode only). * error: raise a ValueError. * new: Create a new sheet, with a name determined by the engine. * replace: Delete the contents of the sheet before writing to it. * overlay: Write contents to the existing sheet without removing the old contents.
If someone could guide me through this I would be highly appreciative :)
Advertisement
Answer
I actually went through the documentation and got it figured.. guess I was too hasty with the question here
Will leave the solution here in hopes it’ll help someone else
with pd.ExcelWriter(file, engine="openpyxl", mode="a", if_sheet_exists="overlay") as writer: df.to_excel(writer, sheet_name=f"{sheets[counter]}")