Python实战:创建、解压ZIP压缩文件

僵卧孤村不自哀,尚思为国戍轮台。夜阑卧听风吹雨,铁马冰河入梦来。 ------宋·陆游《十一月四日风雨大作》

一、压缩指定文件及文件夹为zip

1.1.实现步骤

  1. 文件校验,目标文件夹是否存在。
  2. 创建ZIP文件对象。
  3. 遍历目标文件夹,将文件写入到ZIP对象中.
  4. 遍历完毕,关闭文件流。

1.2.代码实现

import os
import zipfile

# 压缩文件
def zipDir(dirPath, outFileName=None):
    '''
    :param dirPath: 目标文件或文件夹
    :param outFileName: 压缩文件名,默认和目标文件相同
    :return: none
    '''
    # 如果不校验文件也可以生成zip文件,但是压缩包内容为空,所以最好有限校验路径是否正确
    if not os.path.exists(dirPath):
        raise Exception("文件路径不存在:", dirPath)

    # zip文件名默认和被压缩的文件名相同,文件位置默认在待压缩文件的同级目录
    if outFileName == None:
        outFileName = dirPath + ".zip"

    if not outFileName.endswith("zip"):
        raise Exception("压缩文件名的扩展名不正确!因以.zip作为扩展名")

    zip = zipfile.ZipFile(outFileName, "w", zipfile.ZIP_DEFLATED)
    # 遍历文件或文件夹
    for path, dirnames, filenames in os.walk(dirPath):
        fpath = path.replace(dirPath, "")

        for filename in filenames:
            zip.write(os.path.join(path, filename), os.path.join(fpath, filename))
    zip.close()


if __name__ == "__main__":
    zipDir(r"C:\pywork\HelloWorld\HelloWorld")

二、解压ZIP文件

2.1. 实现步骤

  1. 判断文件是否存在
  2. 判断指定压缩文件是否为标准的压缩文件。
  3. 读取ZIP文件对象,遍历文件内容。 将文件解压出来。

2.2.代码实现

import os
import zipfile

def unzipDir(zipFileName, unzipDir=None):
    '''
    :param zipFileName: 目标压缩文件名
    :param unzipDir:  指定解压地址
    :return: none
    '''
    if not os.path.exists(zipFileName):
        raise Exception("文件路径不存在:", zipFileName)

    if not zipfile.is_zipfile(zipFileName):
        raise Exception("目标文件不是压缩文件,无法解压!", zipFileName)

    if unzipDir == None:
        unzipDir = zipFileName.replace(".zip", "")

    with zipfile.ZipFile(zipFileName,"r") as zip:
        for filename in zip.namelist():
            zip.extract(filename, unzipDir)

if __name__ == "__main__":
    unzipDir(r"E:\pywork\HelloWorld\HelloWorld123.zip")
发布了19 篇原创文章 · 获赞 67 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/m1090760001/article/details/104742643