Tuesday, April 26, 2011

[Level 2] how to extract compressed file in Python.

If you want to extract compressed file, you could use zipfile/tarfile to implement.

[zip]
#!/bin/env python
import sys, zipfile, os, os.path

def unzip_file_into_dir(file, dir):
    os.mkdir(dir, 0777)
    zfobj = zipfile.ZipFile(file)
    for name in zfobj.namelist():
        if name.endswith('/'):
            os.mkdir(os.path.join(dir, name))
        else:
            outfile = open(os.path.join(dir, name), 'wb')
            outfile.write(zfobj.read(name))
            outfile.close()

unzip_file_into_dir('/tmp/mywar.war', '/tmp/mywar')

[tar.gz]
#!/bin/env python
import tarfile

def extract_file(file_name):
    tar_file=tarfile.open(name=file_name, mode='r:gz')
    tar_file.extractall()
    tar_file.close()
    pass

extract_file('/tmp/mytar.tar.gz')

Wish this helps.
regards,
Stanley Huang