Python/Pandas 从 csv 创建 zip 文件

Python/Pandas create zip file from csv

是否有人可以提供示例,说明如何使用 Python/Pandas 包从 csv 文件创建 zip 文件? 谢谢

使用

df.to_csv('my_file.gz', compression='gzip')

来自文档:

compression : string, optional a string representing the compression to use in the output file, allowed values are ‘gzip’, ‘bz2’, ‘xz’, only used when the first argument is a filename

查看 zip 文件支持的讨论 here

为了回应 Stefan 的回答,添加“.csv.gz”以使 zip csv 文件正常工作

df.to_csv('my_file.csv.gz', compression='gzip')

希望对你有帮助

在pandas的to_csv()方法中,除了压缩类型(gzzip等)你还可以指定归档文件名——只需要传递dict必要的参数作为 compression 参数:

compression_opts = dict(method='zip',
                        archive_name='out.csv')  
df.to_csv('out.zip', compression=compression_opts)

在上面的示例中,to_csv 方法的第一个参数定义了 [ZIP] 存档文件的名称,dict 的 method 键定义了 [ZIP] 压缩类型和archive_name 字典的键定义存档文件中 [CSV] 文件的名称。

结果:

├─ out.zip
│  └─ out.csv

详见to_csv() pandas docs

Pandas to_csv 压缩存在一些安全漏洞,它会在 Linux 机器上的 zip 存档中留下文件的绝对路径。更不用说有人可能想将文件保存在压缩文件的最高级别。以下函数使用 zipfile 解决了这个问题。最重要的是,它不受 pickle 协议更改(4 到 5)的影响。

from pathlib import Path
import zipfile

def save_compressed_df(df, dirPath, fileName):
    """Save a Pandas dataframe as a zipped .csv file.

    Parameters
    ----------
    df : pandas.core.frame.DataFrame
        Input dataframe.
    dirPath : str or pathlib.PosixPath
        Parent directory of the zipped file.
    fileName : str
        File name without extension.
    """

    dirPath = Path(dirPath)
    path_zip = dirPath / f'{fileName}.csv.zip'
    txt = df.to_csv(index=False)
    with zipfile.ZipFile(path_zip, 'w', zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(f'{fileName}.csv', txt)