Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compress csv file into zip archive directly?

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?

like image 401
zoo zope Avatar asked Sep 22 '14 09:09

zoo zope


People also ask

Can we zip csv file in Linux?

Using gzip and gunzip for Single Files csv and replaces it with the file data. csv. gz. The -v option lets gzip display the compression ratio.

Are CSV files compressed?

CSV files are plain-text files (except when they are compressed), and this makes them ubiquitous, and supported on all platforms and all major software.


1 Answers

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())
like image 164
Maciej Gol Avatar answered Sep 20 '22 12:09

Maciej Gol