python - 在python中压缩excel文件

标签 python excel pandas gzip

现在我的最终输出是 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)

最佳答案

是的,这是可能的。
要创建 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()
这是我用来演示的文件:Link

关于python - 在python中压缩excel文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71181498/

相关文章:

pandas - 绘图的中心调色板 - Seaborn

python - MultiIndex 不起作用的 Pandas shift

python - 如何解析自定义字符串并从该字符串创建字典?

python - 将 statsmodels 与 pyinstaller 一起使用时出错

当 protected View 中的 "Nothing"时,Excel VBA ActiveWorkbook 为 "Enable Editing"

excel - Angular 5 上的 XLSX 缩小版?

excel - 在 COUNTIFS 语句中引用公式日期

python - 无法使用category_encoders的fit_transform对我的数据进行序数编码

python - 如何在人员列表中找到不同国家的数量?

python - 嵌套字典减法