Python3zip 압축 해제 간단한 사용

2668 단어
#!/usr/bin/python
#coding:utf-8
'''
author:[email protected]
date 2015-09-06
version 1.0
python 3.x
'''

import os,os.path
import zipfile

def zip_dir(file_path,zfile_path):
    '''
    function: 
    params:
        file_path: , 
        zfile_path: 
    description: python2 
    '''
    filelist = []
    if os.path.isfile(file_path):
        filelist.append(file_path)
    else :
        for root, dirs, files in os.walk(file_path):
            for name in files:
                filelist.append(os.path.join(root, name))
                print('joined:',os.path.join(root, name),dirs)

    zf = zipfile.ZipFile(zfile_path, "w", zipfile.zlib.DEFLATED)
    for tar in filelist:
        arcname = tar[len(file_path):]
        print(arcname,tar)
        zf.write(tar,arcname)
    zf.close()

def unzip_file(zfile_path, unzip_dir):
    '''
    function: 
    params:
        zfile_path: 
        unzip_dir: 
    description:
    '''
    try:
        with zipfile.ZipFile(zfile_path) as zfile:
            zfile.extractall(path=unzip_dir)
    except zipfile.BadZipFile as e:
        print (zfile_path+" is a bad zip file ,please check!")

if __name__ == '__main__':
    #zip_dir(r'/tmp/xungou',r'/tmp/xungou.zip')
    unzip_file(r'/tmp/xungou.zip',r'/tmp/xungou')

좋은 웹페이지 즐겨찾기