How to compress a folder and all of its sub directories and files into a zip file?

Brian van den Broek bvande at po-box.mcgill.ca
Tue Jun 28 03:44:12 EDT 2005


could ildg said unto the world upon 28/06/2005 03:29:
> but the file is just stored,
> and not compressed.
> 
> On 6/28/05, could ildg <could.net at gmail.com> wrote:
> 
>>Thank you,
>>it works~~
>>
>>On 6/29/05, Peter Szinek <peter at rt.sk> wrote:
>>
>>>Hi,
>>>
>>>What about this:
>>>
>>>import os,zipfile
>>>from os.path import join
>>>
>>>
>>>zip = zipfile.ZipFile("myzipfile.zip", 'w')
>>>for root, dirs, files in os.walk('.'):
>>>     for fileName in files:
>>>         zip.write(join(root,fileName))
>>>zip.close()
>>>
>>>Maybe it zips also the myzipfile.zip ;-)
>>>Probably this is not needed, so an additional test (something like
>>>fileName != 'myfile.zip' would be needed.
>>>
>>>HTH,
>>>Peter
>>>
>>>could ildg wrote:
>>>
>>>>I want to compress a folder and all of its sub files including empty folders
>>>>into a zip file. what's the pythonic way to do this?
>>>>
>>>>Thanks in advance.
>>>
>>>

This thread got me to read the relevant docs:

7.18.1 ZipFile Objects
"class ZipFile( 	file[, mode[, compression]])
     Open a ZIP file, where file can be either a path to a file (a 
string) or a file-like object. The mode parameter should be 'r' to 
read an existing file, 'w' to truncate and write a new file, or 'a' to 
append to an existing file. For mode is 'a' and file refers to an 
existing ZIP file, then additional files are added to it. If file does 
not refer to a ZIP file, then a new ZIP archive is appended to the 
file. This is meant for adding a ZIP archive to another file, such as 
python.exe. Using

cat myzip.zip >> python.exe

     also works, and at least WinZip can read such files. compression 
is the ZIP compression method to use when writing the archive, and 
should be ZIP_STORED or ZIP_DEFLATED; unrecognized values will cause 
RuntimeError to be raised. If ZIP_DEFLATED is specified but the zlib 
module is not available, RuntimeError is also raised. The default is 
ZIP_STORED."
http://docs.python.org/lib/zipfile-objects.html

So, it would appear that compression requires a 3rd party module, not 
included in Python (and not present on my Windows box).

I'm presently filing a bug suggesting this be made a touch more 
explicit in the zlib docs.

Best to all,

Brian vdB




More information about the Python-list mailing list