I generate several 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 squeeze them.
Using the gzip module is pretty simple:
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 to be in the "zip" format.
I tried the zipfile module, but I cannot write files directly to the zip archive.
Instead, I need to write the csv file to disk, compress them in a zip file using the following code, and then delete the csv file.
with ZipFile(zipfilepath, 'w') as zipfile: zipfile.write(csvfilepath, csvfilename, ZIP_DEFLATED)
How to write a csv file directly to compressed zip, similar to gzip?
python gzip csv zipfile
zoo zope
source share