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

我使用以下代码动态生成许多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)

为了节省空间,我想压缩它们.
使用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)

但我想要’zip’格式的文件.

我尝试了zipfile模块,但我无法直接将文件写入zip存档.

相反,我必须将csv文件写入磁盘,使用以下代码在zip文件中压缩它们,然后删除csv文件.

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

如何将csv文件直接写入类似于gzip的压缩zip?

使用 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())
相关文章
相关标签/搜索