unziping a file in python..

MRAB google at mrabarnett.plus.com
Mon Mar 2 11:13:39 EST 2009


Luis Zarrabeitia wrote:
> Quoting MRAB <google at mrabarnett.plus.com>:
>> Steven D'Aprano wrote:
>>> A quick and dirty solution would be something like this:
>>>
>>> zf = zipfile.ZipFile('Archive.zip')
>>> for name in zf.namelist():
>>>     open(name, 'w').write(zf.read(name))
>>>
>> You might want to specify an output folder (and the data might be binary
>> too):
>>
>> zf = zipfile.ZipFile('Archive.zip')
>> for name in zf.namelist():
>>      open(os.path.join(output_folder, name), 'wb').write(zf.read(name))
>>
> 
> Question here... wouldn't you also need to create all the intermediate folders
> from "output_folder" to "output_folder/name" (assuming that 'name' has several
> path parts in it)? Is there any elegant way to do it? 
> 
Of course there is; this is Python! :-)

 > (is there any way to make os.mkdir behave like mkdir -p?)
 >

Perhaps:

zf = zipfile.ZipFile('Archive.zip')
for name in zf.namelist():
     new_path = os.path.join(output_folder, name)
     data = zf.read(name)
     try:
         open(new_path, 'wb').write(data)
     except IOError:
         # Create intermediate folders and try again
         os.makedirs(os.path.dirname(new_path))
         open(new_path, 'wb').write(data)



More information about the Python-list mailing list