Python文件夹压缩

使用Python实现文件夹的压缩,做个记录,以备后查。

#!/usr/bin/python
# -*- coding:UTF-8 -*-

import sys
import os,os.path
import shutil
import argparse
import zipfile

curDir=os.path.dirname(os.path.realpath(__file__))
goalDir=curDir+'\\zipFiles'

def checkGoalDir(dir):
    if os.path.exists(dir):
        shutil.rmtree(dir)
    if not os.path.exists(dir):
        os.mkdir(dir)

def delFile(fileName):
    if os.path.exists(fileName):
        os.remove(fileName)

# 循环递归遍历文件夹
def getFloderFiles(fileDir):
    #记录待便利文件夹信息
    arr=[fileDir]
    fs = os.listdir(fileDir)
    for dir in fs:
        tmp_path = os.path.join(fileDir, dir)
        if os.path.isfile(tmp_path):
            arr.append(tmp_path)
        else:
            # 是文件夹,则递归调用
            arr.extend(getFloderFiles(tmp_path))
    return arr

def zipFloderFiles(fatherPath,srcDir,zipFileName):
    tmpArr=getFloderFiles(srcDir)
    file=zipfile.ZipFile(zipFileName+'.zip','w')
    tmpAdded=[]
    for fullPath in tmpArr :
        tp=os.path.dirname(fullPath)
        fileName=fullPath.replace(fatherPath,'')
        file.write(fullPath,fileName)
    file.close()

def myLog(logStr):
    print('------'+logStr+'------')

def init(path):
    checkGoalDir(curDir+'\\zipFiles')

    myLog('start zip')

    #获取目标目录的上一级目录
    fatherPath=os.path.abspath(os.path.dirname(os.path.dirname(path)))
    #获取目标目录名称
    zipName=path.replace(fatherPath,'')
    zipName=zipName.replace('\\','')

    zipFloderFiles(fatherPath,path,goalDir+'\\'+zipName)
    myLog('zip success')

if __name__=='__main__':
    parser = argparse.ArgumentParser(description='Process zip floders root path.')
    parser.add_argument('-p', '--path', help='floder path')
    args = parser.parse_args()
    init(args.path+'\\')

注意:需要将文件夹的信息写入压缩文件,否则使用一些工具解压可能会出现问题。

 比如测试文件夹如下:

压缩后的文件查看信息应该如下【要有文件夹的信息】:

 

参考资料:

python使用zipfile模块来压缩文件时,解决如何不带入路径的问题

猜你喜欢

转载自blog.csdn.net/auccy/article/details/120285376