[英]Save Dataframe changes to the same xlsx file using pandas (append)
嘗試將更改保存到同一個 xlsx 文件而不覆蓋它,
我用什么來讀取文件
import pandas as pd
file = 'path'
df = pd.read_excel(f"{file}", 'sheet')
這已經覆蓋了我的文件
df.to_excel(path)
根據 Pandas 團隊,可以使用以下內容
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.
如果有人可以指導我解決這個問題,我將不勝感激:)
我實際上瀏覽了文檔並弄清楚了..我猜我在這里問這個問題太倉促了
將解決方案留在這里,希望它能幫助別人
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.