Extracting zip files containing directories with ZipFile

M

Márcio Faustino

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)
#----------

Thanks,
 
M

MRAB

Márcio Faustino said:
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.
 

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

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top