Python Tutorial

Showing posts with label Zip/Unzip. Show all posts
Showing posts with label Zip/Unzip. Show all posts

Thursday, August 26, 2010

Python Unzip a tar file

'''
   This class use for Unzip a tar file
'''

import os
import tarfile
import sys

class UnZipFolder():
    def __init__(self, location):
        self.location=location
        # Set output directory here
        self.outputLocation="C:/"

    def decompress(self):
        try:
            if os.path.exists(self.location):
                decompressTar = tarfile.open(self.location)
                decompressTar.extractall(self.outputLocation)
                decompressTar.close()
                print "Extracted"
            else:
                print "No Such Folder"
        except:
            print str(sys.exc_info())
            
if __name__=='__main__':
    # Set input directory here
    location="C:/test.tar"
    unZipFolder=UnZipFolder(location)
    unZipFolder.decompress()

python zip a folder or file



Zip a folder or file is very easy in python. You need to set variable location by your file or folder location.

'''
    This class use for zip a folder
    - Create a folder named "testFolder" on C drive or reset the location
'''

import os
import tarfile
import sys

class ZipFolder():
    # Constructor of ZipFolder
    def __init__(self, location):
        self.location=location

    def makeCompress(self):
        try:
            if os.path.exists(self.location):
                compressTar = tarfile.open(self.location+".tar", "w:gz")
                compressTar.add(self.location)
                compressTar.close()
                print "Compress complete ",self.location
            else:
                print " (ZipFile)No Such Folder ",self.location 
        except:
            print str(sys.exc_info())

if __name__=='__main__':
    location="C:/testFolder"
    zipFolder=ZipFolder(location)
    zipFolder.makeCompress()