Recursive zipping of Directories in Windows

Larry Bates larry.bates at websafe.com
Thu Feb 1 16:39:26 EST 2007


Jandre wrote:
> Hi
> 
> I am a python novice and I am trying to write a python script (most of
> the code is borrowed) to Zip a directory containing some other
> directories and files. The script zips all the files fine but when it
> tries to zip one of the directories it fails with the following
> error:
> "IOError: [Errno 13] Permission denied: 'c:\\aaa\\temp'"
> 
> The script I am using is:
> 
> import zipfile, os
> 
> def toZip( directory, zipFile ):
>     """Sample for storing directory to a ZipFile"""
>     z = zipfile.ZipFile(
>         zipFile, 'w', compression=zipfile.ZIP_DEFLATED
>     )
>     def walker( zip, directory, files, root=directory ):
>         for file in files:
>             file = os.path.join( directory, file )
>             # yes, the +1 is hacky...
>             archiveName = file[len(os.path.commonprefix( (root,
> file) ))+1:]
>             zip.write( file, archiveName, zipfile.ZIP_DEFLATED )
>             print file
>     os.path.walk( directory, walker, z  )
>     z.close()
>     return zipFile
> 
> 
> if __name__ == "__main__":
>     toZip( 'c:\\aaa', 'c:\\aaa\\test.zip' )
> 
> I have tried to set the permissions on the folder, but when I check
> the directory permissions it is set back to "Read Only"
> 
> Any suggestions?
> 
> Thanks
> Johan Balt
> 
Couple of quick suggestions that may help:

1) don't use 'file' as a variable name. It will mask
the builtin file function.  If it hasn't bitten you before
it will if you keep doing that.

2) If you put the target .zip file in the directory you are
backing what do you expect the program to do when it comes
to the file you are creating as you walk the directory?  You
haven't done anything to 'skip' it.

3) Your commonprefix and +1 appears to result in same
information that the easier to use os.path.basename()
would give you.  Double check me on that.

I don't see anything that references C:\\aaa\temp in your
code.  Does it exist on your hard drive?  If so does it
maybe contain temp files that are open?  zipfile module
can't handle open files.  You must use try/except to
catch these errors.

Hope info helps.

-Larry



More information about the Python-list mailing list