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
Python/Pandas create zip file from csv
提问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 zip
files here.
请参阅此处对zip
文件支持的讨论。
回答by Anton Ermakov
In the to_csv()
method of pandas v.1.0.3, besides the compression type (gz
, zip
etc) you can specify the archive file name - just pass the dict with necessary params as the compression
parameter:
在to_csv()
pandas v.1.0.3的方法中,除了压缩类型(等)之外gz
,zip
您还可以指定存档文件名 - 只需将带有必要参数的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_csv
method defines the name of the [ZIP] archive file, the method
key of the dict defines [ZIP] compression type and the archive_name
key of the dict defines the name of the [CSV] file inside the archive file.
在上面的例子中,该to_csv
方法的第一个参数定义了 [ZIP] 存档文件的名称,method
dict的键定义了 [ZIP] 压缩类型,archive_name
dict的键定义了压缩包中的 [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
希望有帮助