Python Tutorial

Thursday, August 26, 2010

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()

0 comments:

Post a Comment