Welcome, guest | Sign In | My Account | Store | Cart

This recipe can be used to extract any zip or tar.gz/tar.bz2 file.

Python, 23 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import os
import tarfile
import zipfile

def extract_file(path, to_directory='.'):
    if path.endswith('.zip'):
        opener, mode = zipfile.ZipFile, 'r'
    elif path.endswith('.tar.gz') or path.endswith('.tgz'):
        opener, mode = tarfile.open, 'r:gz'
    elif path.endswith('.tar.bz2') or path.endswith('.tbz'):
        opener, mode = tarfile.open, 'r:bz2'
    else: 
        raise ValueError, "Could not extract `%s` as no appropriate extractor is found" % path
    
    cwd = os.getcwd()
    os.chdir(to_directory)
    
    try:
        file = opener(path, mode)
        try: file.extractall()
        finally: file.close()
    finally:
        os.chdir(cwd)

Use it like this:

>>> extract_file("Python-2.6.1.tar.gz")
>>> extract_file("linux-2.7.1-2.tar.bz2")
>>> extract_file("diveintopython-word-5.4.zip")

4 comments

david.gaarenstroom 12 years, 8 months ago  # | flag

You forget to use mode?

Sridhar Ratnakumar (author) 12 years, 7 months ago  # | flag

@david - fixed now.

Sridhar Ratnakumar (author) 11 years, 10 months ago  # | flag

A better version of this recipe can be found in setuptools.archive_util (it uses open to verify file type, instead of using file extensions which can be unreliable).