Extracting zip files containing directories with ZipFile

MRAB google at mrabarnett.plus.com
Sun Apr 12 18:01:46 CEST 2009


Márcio Faustino wrote:
> Hi,
> 
> Does the ZipFile class correctly handles directories contained within
> zip files?
> 
> For example, calling "extractall" on an archive with only "folder/
> file.txt" in it results in an IOError saying "No such file or
> directory" for "./folder/file.txt", because it created a file named
> "folder" instead of a directory. (I've tested this with version 2.6.1
> on Windows XP.) However, changing that method to the following, seems
> to solve this particular problem:
> 
> #----------
> def extractall(self, path = os.path.curdir, members = None, password =
> None):
>     if members is None:
>         members = self.namelist()
> 
>     # Place directories first to create them before extracting any
> file.
>     members.sort()
> 
>     for name in members:
>         if name.endswith('/'):
>             os.makedirs(os.path.join(path, name))
>         else:
>             self.extract(name, path, password)
> #----------
> 
Strictly speaking, zip files don't contain nested folders, but only a
flat list of files.

However, by convention a folder hierarchy is shown by the use of slashes
in the names eg. "foo/bar.txt" is a folder "foo" containing a file
"bar.txt". You can also represent an empty folder with a (zero-length)
file ending with a slash, eg "foo/" is an empty folder "foo".

Just create any intermediate folders on demand if they don't already
exist.



More information about the Python-list mailing list