Python/Pandas 从 csv 创建 zip 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37754165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:21:54  来源:igfitidea点击:

Python/Pandas create zip file from csv

pythoncsvpandaszipcompression

提问by Felix

Is anyone can provide example how to create zip file from csv file using Python/Pandas package? Thank you

任何人都可以提供示例如何使用 Python/Pandas 包从 csv 文件创建 zip 文件?谢谢

回答by Stefan

Use

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

From the docs:

从文档:

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

压缩:字符串,可选的字符串,表示在输出文件中使用的压缩,允许的值为'gzip'、'bz2'、'xz',仅在第一个参数是文件名时使用

See discussion of support of zipfiles here.

请参阅此处zip文件支持的讨论。

回答by Anton Ermakov

In the to_csv()method of pandas v.1.0.3, besides the compression type (gz, zipetc) you can specify the archive file name - just pass the dict with necessary params as the compressionparameter:

to_csv()pandas v.1.0.3的方法中,除了压缩类型(等)之外gzzip您还可以指定存档文件名 - 只需将带有必要参数的dict作为compression参数传递:

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

In the example above, the first argument of the to_csvmethod defines the name of the [ZIP] archive file, the methodkey of the dict defines [ZIP] compression type and the archive_namekey of the dict defines the name of the [CSV] file inside the archive file.

在上面的例子中,该to_csv方法的第一个参数定义了 [ZIP] 存档文件的名称,methoddict的键定义了 [ZIP] 压缩类型,archive_namedict的键定义了压缩包中的 [CSV] 文件的名称。存档文件。

Result:

结果:

├─ out.zip
│  └─ out.csv

See details in to_csv() pandas docs

to_csv() Pandas文档中查看详细信息

回答by Yi Xiang Chong

In response to Stefan's answer, add '.csv.gz' for the zip csv file to work

为了回应 Stefan 的回答,为 zip csv 文件添加“.csv.gz”

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

Hope that helps

希望有帮助