Zip directory and unzip file in Python way

Author Joe Date one year ago
Views 636 Reviews 0
Rating Favoured
0
import os,os.path
import zipfile

def zipDir(dirName,zipFileName):
    fileList = []
    if os.path.isfile(dirName):
        fileList.append(dirName)
    else :
        for root, dirs, files in os.walk(dirName):
            for name in files:
                fileList.append(os.path.join(root, name))

    zf = zipfile.ZipFile(zipFileName, "w", zipfile.zlib.DEFLATED)
    for tar in fileList:
        arcName = tar[len(dirName):]
        zf.write(tar,arcName)
    zf.close()


def unzipFile(zipFileName, unZipTargetDir):
    if not os.path.exists(unZipTargetDir):
        os.mkdir(unZipTargetDir, 0777)
    zfObj = zipfile.ZipFile(zipFileName)
    for name in zfObj.namelist():
        if name.endswith(os.path.sep):
            os.mkdir(os.path.join(unZipTargetDir, name))
        else:
            ext_filename = os.path.join(unZipTargetDir, name)
            ext_dir= os.path.dirname(ext_filename)
            if not os.path.exists(ext_dir) : os.mkdir(ext_dir,0777)
            outfile = open(ext_filename, 'wb')
            outfile.write(zfObj.read(name))
            outfile.close()

if __name__ == '__main__':
    zipDir(u'/home/joe/Learning',u'/home/joe/Learning/leaning.zip')
    unzipFile(u'/home/joe/Learning/leaning.zip',u'/home/joe/Learning2')

0 comments

Your rating:


Back to reviews top | Back to top
© OSTree(Open Source Tree Community) | About OSTree | Advertisement | Feedback