Python combat: create, extract the ZIP compressed files

Lying on Gucun not from sorrow, still thinking Shu round table for the country. Yelan lying listening to the wind and rain, cavalry glacier fall asleep to. ------ Song Lu, "November 4 big wind and rain."

A compression specified files and folders into a zip

1.1. Implementation steps

  1. File checksum, the target folder exists.
  2. Create a ZIP file object.
  3. Traversing the destination folder, write files to ZIP object.
  4. Traversal is complete, close the file stream.

1.2. Code implementation

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

Second, extract the ZIP file

2.1. Implementation steps

  1. Determine whether a file exists
  2. Determine whether the specified file compression standard compressed files.
  3. Read ZIP file objects, traverse the contents of the file. The extract from the file.

2.2 code implementation

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")
Published 19 original articles · won praise 67 · views 20000 +

Guess you like

Origin blog.csdn.net/m1090760001/article/details/104742643