isaapm
isaapm

Reputation: 157

zip downloaded csv file

I'm trying to download a csv file and zip it before saving it. The code I'm using is:

req = urllib2.Request(url)
fh = urllib2.urlopen(req)
with contextlib.closing(ZipFile("test.csv.zip", "w", zipfile.ZIP_STORED)) as f:
    f.write(fh.read())
    f.close()

What this does is to print the contents of the csv file to stdout and create an empty zipfile.

Any ideas of what could be wrong?

Thanks, Isaac

Upvotes: 3

Views: 196

Answers (1)

mhawke
mhawke

Reputation: 87064

Take a look at the documentation for ZipFile.write(). Here is the function signature:

ZipFile.write(filename[, arcname[, compress_type]])

The first argument should be the file name of the file that you are adding to the zip archive, not the contents of the file. Instead you are passing the entire contents of the downloaded resource as the file name and, because that will likely be illegal (too long), you see the file contents dumped as part of the error message of the raised exception.

To fix this you need to use is ZipFile.writestr():

req = urllib2.Request(url)
fh = urllib2.urlopen(req)
with ZipFile("test.csv.zip", "w", zipfile.ZIP_STORED) as f:
    f.writestr('test.csv', fh.read())

If it is your intention to compress only a single file, you probably don't need to use a zip archive, and you might be better off using gzip or bzip2.

Upvotes: 2

Related Questions