Adding to a zip file

D

Dennis Hotson

I'm having trouble adding a file to a .zip file using python2.3.
The write method of a ZipFile object needs a filename in
order to add a file to the archive.

The problem is that I want to add a 'file-like' object... ie the 'file'
doesn't have a real filename.

Any suggestions on what I could do? :)

Oh and also, I looked at os.tmpname() to try and create a temporary
file.. but I keep getting warnings about it's security. Does anyone know
how safe it would be to use it?
 
P

Peter Hansen

Dennis said:
I'm having trouble adding a file to a .zip file using python2.3.
The write method of a ZipFile object needs a filename in
order to add a file to the archive.

The problem is that I want to add a 'file-like' object... ie the 'file'
doesn't have a real filename.

Any suggestions on what I could do? :)

Look for the writestr() method of the ZipFile object.
Oh and also, I looked at os.tmpname() to try and create a temporary
file.. but I keep getting warnings about it's security. Does anyone know
how safe it would be to use it?

Exactly as safe as the docs suggest? In any case, I would
suggest looking at the "tempfile" module instead.

-Peter
 
I

Istvan Albert

Dennis said:
Ahhh... works a treat!

Check the compression rates within the zipfile. I had some
problems with the writestr method:

----

import zipfile, time

zfile = zipfile.ZipFile('test.zip', 'w', zipfile.ZIP_DEFLATED)
data = 'whatever ' * 100
zinfo = zipfile.ZipInfo('message.txt', time.localtime()[:6])
zfile.writestr(zinfo, data)
zfile.close

-----

On my windows system this generates a test.zip file that
contains the message.txt entry but without compression!
(0% compression ratio).

I wasn't motivated enough to find out what exactly is happening
because the file based methods worked properly and turned out
to be a better solution for my problem.

Istvan.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,162
Latest member
GertrudeMa
Top