如何压缩csv文件到zip存档中直接? [英] How to compress csv file into zip archive directly?

查看:758
本文介绍了如何压缩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()
数据中的行:
csvwrite.writerow(row)

为了节省空间,我想压缩它们。

使用 gzip 模块是很容易的:

 与gzip.open(foo.gz,w)as csvfile:
csvwrite = csv。 DictWriter(csvfile,delimiter =',',fieldnames = fieldnames)
csvwrite.writeheader()
数据行:
csvwrite.writerow(row)



但我想要的文件为'zip'格式。



zipfile 模块,但我无法直接将文件写入zip存档。



将csv文件压缩到磁盘,使用以下代码将其压缩为zip文件,然后删除csv文件。

 使用ZipFile zipfilepath,'w')作为zipfile:
zipfile.write(csvfilepath,csvfilename,ZIP_DEFLATED)

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

解决方案

使用 cStringIO.StringIO 对象模仿文件:使用ZipFile(your_zip_file,'w',ZIP_DEFLATED)作为zip_file:

 
string_buffer = StringIO b writer = csv.writer(string_buffer)

#使用writer对象写入数据。

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


I am generating a number of csv files dynamically, using the following code:

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:

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.

I tried the zipfile module, but I am unable to directly write files into the zip archive.

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.

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?

解决方案

Use the cStringIO.StringIO object to imitate a file:

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())

这篇关于如何压缩csv文件到zip存档中直接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆