Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unzip a file with Python 2.4?

I'm having a hard time figuring out how to unzip a zip file with 2.4. extract() is not included in 2.4. I'm restricted to using 2.4.4 on my server.

Can someone please provide a simple code example?

like image 401
Tapefreak Avatar asked Oct 18 '11 11:10

Tapefreak


People also ask

What is Python ZIP file?

Python's zipfile is a standard library module intended to manipulate ZIP files. This file format is a widely adopted industry standard when it comes to archiving and compressing digital data. You can use it to package together several related files.

How do I zip a file in Python using ZIP file?

To compress individual files into a ZIP file, create a new ZipFile object and add the files you want to compress with the write() method. With zipfile. ZipFile() , specify the path of a newly created ZIP file as the first parameter file , and set the second parameter mode to 'w' (write).


2 Answers

You have to use namelist() and extract(). Sample considering directories

import zipfile import os.path import os zfile = zipfile.ZipFile("test.zip") for name in zfile.namelist():   (dirname, filename) = os.path.split(name)   print "Decompressing " + filename + " on " + dirname   if not os.path.exists(dirname):     os.makedirs(dirname)   zfile.extract(name, dirname) 
like image 77
Vinko Vrsalovic Avatar answered Oct 13 '22 22:10

Vinko Vrsalovic


There's some problem with Vinko's answer (at least when I run it). I got:

IOError: [Errno 13] Permission denied: '01org-webapps-countingbeads-422c4e1/' 

Here's how to solve it:

# unzip a file def unzip(path):     zfile = zipfile.ZipFile(path)     for name in zfile.namelist():         (dirname, filename) = os.path.split(name)         if filename == '':             # directory             if not os.path.exists(dirname):                 os.mkdir(dirname)         else:             # file             fd = open(name, 'w')             fd.write(zfile.read(name))             fd.close()     zfile.close() 
like image 38
Ovilia Avatar answered Oct 14 '22 00:10

Ovilia