[英]Save Dataframe changes to the same xlsx file using pandas (append)
Trying to save changes to the same xlsx file without overwriting it,尝试将更改保存到同一个 xlsx 文件而不覆盖它,
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根据 Pandas 团队,可以使用以下内容
https://github.com/pandas-dev/pandas/blob/main/pandas/io/excel/_base.py#L800-L814 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:)如果有人可以指导我解决这个问题,我将不胜感激:)
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]}")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.