現在我的最終輸出是 excel 格式。我想使用 gzip 壓縮我的 excel 檔案。有沒有辦法做到這一點?
import pandas as pd
import gzip
import re
def renaming_ad_unit():
with gzip.open('weekly_direct_house.xlsx.gz') as f:
df = pd.read_excel(f)
result = df['Ad unit'].to_list()
for index, a_string in enumerate(result):
modified_string = re.sub(r"\([^()]*\)", "", a_string)
df.at[index,'Ad unit'] = modified_string
return df.to_excel('weekly_direct_house.xlsx',index=False)
uj5u.com熱心網友回復:
是的,這是可能的。
要創建 gzip 檔案,您可以像這樣打開檔案:
with gzip.open('filename.xlsx.gz', 'wb') as f:
...
不幸的是,當我嘗試這個時,我發現我得到了錯誤OSError: Negative seek in write mode。這是因為 Pandas excel writer 在寫入時會在檔案中向后移動,并使用多次傳遞來寫入檔案。gzip 模塊不允許這樣做。
為了解決這個問題,我創建了一個臨時檔案,并在那里撰寫了 excel 檔案。然后,我讀回文??件,并將其寫入壓縮存檔。
我寫了一個簡短的程式來證明這一點。它從 gzip 存檔中讀取一個 excel 檔案,將其列印出來,然后將其寫回另一個 gzip 檔案。
import pandas as pd
import gzip
import tempfile
def main():
with gzip.open('apportionment-2020-table02.xlsx.gz') as f:
df = pd.read_excel(f)
print(df)
with tempfile.TemporaryFile() as excel_f:
df.to_excel(excel_f, index=False)
with gzip.open('output.xlsx.gz', 'wb') as gzip_f:
excel_f.seek(0)
gzip_f.write(excel_f.read())
if __name__ == '__main__':
main()
這是我用來演示的檔案:鏈接
uj5u.com熱心網友回復:
您還可以使用io.BytesIO在記憶體中創建檔案并在此檔案中寫入 excel,然后將此檔案作為 gzip 寫入磁盤。
我使用來自 Nick ODell 答案的 excel 檔案的鏈接。
import pandas as pd
import gzip
import io
df = pd.read_excel('https://www2.census.gov/programs-surveys/decennial/2020/data/apportionment/apportionment-2020-table02.xlsx')
buf = io.BytesIO()
df.to_excel(buf)
buf.seek(0) # move to the beginning of file
with gzip.open('output.xlsx.gz', 'wb') as f:
f.write(buf.read())
類似于 Nick ODell 的回答。
import pandas as pd
import gzip
import io
df = pd.read_excel('https://www2.census.gov/programs-surveys/decennial/2020/data/apportionment/apportionment-2020-table02.xlsx')
with io.BytesIO() as buf:
df.to_excel(buf)
buf.seek(0) # move to the beginning of file
with gzip.open('output.xlsx.gz', 'wb') as f:
f.write(buf.read())
在 Linux 上測驗
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/428727.html
