简体   繁体   English

如何将csv文件直接压缩成zip存档?

[英]How to compress csv file into zip archive directly?

I am generating a number of csv files dynamically, using the following code:我正在使用以下代码动态生成多个 csv 文件:

import csv
fieldnames = ['foo1', 'foo2', 'foo3', 'foo4']
with open(csvfilepath, 'wb') as csvfile:
    csvwrite = csv.DictWriter(csvfile, delimiter=',', fieldnames=fieldnames)
    csvwrite.writeheader()
    for row in data:
        csvwrite.writerow(row)

To save space, I want to compress them.为了节省空间,我想压缩它们。
Using the gzip module is quite easy:使用gzip模块非常简单:

with gzip.open("foo.gz", "w") as csvfile :
    csvwrite = csv.DictWriter(csvfile, delimiter=',', fieldnames=fieldnames)
    csvwrite.writeheader()
    for row in data:
        csvwrite.writerow(row)

But I want the file in 'zip' format.但我想要“zip”格式的文件。

I tried the zipfile module, but I am unable to directly write files into the zip archive.我尝试了zipfile模块,但无法直接将文件写入 zip 存档。

Instead, I have to write the csv file to disk, compress them in a zip file using following code, and then delete the csv file.相反,我必须将 csv 文件写入磁盘,使用以下代码将它们压缩为 zip 文件,然后删除 csv 文件。

with ZipFile(zipfilepath, 'w') as zipfile:
    zipfile.write(csvfilepath, csvfilename, ZIP_DEFLATED)

How can I write a csv file directly to a compressed zip similar to gzip?如何将 csv 文件直接写入类似于 gzip 的压缩 zip?

Use the cStringIO.StringIO object to imitate a file:使用cStringIO.StringIO对象模仿一个文件:

with ZipFile(your_zip_file, 'w', ZIP_DEFLATED) as zip_file:
    string_buffer = StringIO()
    writer = csv.writer(string_buffer)

    # Write data using the writer object.

    zip_file.writestr(filename + '.csv', string_buffer.getvalue())

Thanks kroolik It's done with little modification.谢谢 kroolik 它几乎没有修改就完成了。

with ZipFile(your_zip_file, 'w', ZIP_DEFLATED) as zip_file:
    string_buffer = StringIO()
    csvwriter = csv.DictWriter(string_buffer, delimiter=',', fieldnames=fieldnames)
    csvwrite.writeheader()
    for row in cdrdata:
        csvwrite.writerow(row)
    zip_file.writestr(filename + '.csv', string_buffer.getvalue())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM