Python 压缩文件夹

Python 压缩文件夹

生成测试文件夹

可以先使用该脚本生成测试文件夹,也可以直接用自己的文件夹

import os
import shutil


def main():
    shutil.rmtree('AAA')
    os.makedirs("AAA")
    os.makedirs("AAA/BBB")
    os.makedirs("AAA/BBB/EEE")
    os.makedirs("AAA/BBB/FFF")
    os.makedirs("AAA/CCC")
    os.makedirs("AAA/CCC/GGG")
    os.makedirs("AAA/CCC/GGG/WWW")
    os.makedirs("AAA/CCC/HHH")

    with open('AAA/AAA1.txt', 'w') as f:
        f.write('txt_file_content')

    with open('AAA/AAA2.txt', 'w') as f:
        f.write('txt_file_content')

    with open('AAA/BBB/BBB1.txt', 'w') as f:
        f.write('txt_file_content')

    with open('AAA/BBB/BBB2.txt', 'w') as f:
        f.write('txt_file_content')

    with open('AAA/CCC/CCC1.txt', 'w') as f:
        f.write('txt_file_content')

    with open('AAA/BBB/EEE/EEE1.txt', 'w') as f:
        f.write('txt_file_content')
    with open('AAA/BBB/FFF/FFF1.txt', 'w') as f:
        f.write('txt_file_content')

    with open('AAA/CCC/HHH/HHH1.txt', 'w') as f:
        f.write('txt_file_content')


if __name__ == '__main__':
    main()

压缩文件夹

可以传递绝对路径和相对路径

测试环境是windows和python3.6

import os.path
import zipfile


def zip_dir(dir_path: str, save_path: str):
    dir_path = os.path.abspath(dir_path)
    save_path = os.path.abspath(save_path)
    if not os.path.exists(os.path.dirname(save_path)):
        os.makedirs(os.path.dirname(save_path))
    with zipfile.ZipFile(save_path, "w", zipfile.ZIP_DEFLATED) as f:
        for path, dir_names, filenames in os.walk(dir_path):
            # print(f'path:{path}')
            # print(f'dir_nams:{dir_names}')
            # print(f'filenames:{filenames}')
            for dir_name in dir_names:
                save_folder = os.path.join(path, dir_name)
                # print(f'save_folder:{save_folder}')
                save_folder = save_folder.replace(os.path.dirname(dir_path) + os.sep, '')
                # print(f'save_folder:{save_folder}')
                f.write(save_folder)

            for filename in filenames:
                save_file = os.path.join(path, filename)
                save_file = save_file.replace(os.path.dirname(dir_path) + os.sep, '')
                f.write(save_file)
    print(f"save to path:{save_path}")


def main():
    zip_dir("AAA", 'VV/a.zip')
    zip_dir("E:\gitee_code\learn-python\备份数据库和文件夹\AAA", 'b.zip')


if __name__ == '__main__':
    main()

运行

测试目录结构

image-20230912153151985

生成出的压缩包

image-20230912153551379

posted @ 2023-09-12 15:37  南风丶轻语  阅读(82)  评论(0编辑  收藏  举报