介绍

        实现压缩打包文件/文件夹方法,分两种类型处理打包文件是需要传入文件的路径打包文件夹是传入文件夹路径

实现压缩打包代码

import os
import shutil
from zipfile import ZipFile


# 压缩打包文件
def compress_pack_file(zip_path, compress_type="file", file_path_list=[], folder_path=""):
    """
    传入的是文件路径列表则压缩指定文件,传入的是文件夹则压缩该文件夹
    :param zip_path: 需要写入的zip文件路径
    :param compress_type: 压缩的类型:"file":压缩指定文件;"folder":压缩文件夹
    :param file_path_list: 文件路径列表
    :param folder_path: 文件夹路径
    :return:
    """
    data_dict = {"data": "", "warning_info": "", "error_info": "", }
    try:
        if compress_type == "file":
            if not len(file_path_list):
                data_dict["error_info"] = "没有文件需要压缩打包"
                return data_dict

            with ZipFile(zip_path, 'w') as zip_file:
                for file_path in file_path_list:
                    if os.path.exists(file_path):
                        file_name = os.path.basename(file_path)
                        zip_file.write(file_path, file_name)
                    else:
                        data_dict["warning_info"] += f"【{file_path}】无法压缩打包" + "n"
        elif compress_type == "folder":
            if zip_path == folder_path:
                data_dict["error_info"] = "不能压缩打包"
                return data_dict
            file_name_without_ext = os.path.splitext(zip_path)[0]
            shutil.make_archive(file_name_without_ext, 'zip', folder_path)
            
        else:
            data_dict["error_info"] = f"所选压缩打包类型无效"

    except Exception as e:
        data_dict["error_info"] = f"执行压缩打包失败"
        print(e)

    return data_dict


if __name__ == '__main__':
    f_path = r"D:BusinessProject结果文件2023-12-01"
    z_p = r"D:BusinessProject结果文件2023-12-01压缩文件.zip"
    f_l = [
        'D:\BusinessProject\结果文件\2023-12-01\2023-11-29-2023-11-29-官方旗舰店--2023-12-01_10:57.xlsx',
        'D:\BusinessProject\官方旗舰店--2023-12-01_11:00.xlsx',
        'D:\BusinessProject\官方旗舰店--2023-12-01_11:01.xlsx',
        'D:\BusinessProject\官方旗舰店--2023-12-01_11:02.xlsx',
        'D:\BusinessProject\卧室家具旗舰店--2023-12-01_11:01.xlsx',
        'D:\BusinessProject\卧室家具旗舰店--2023-12-01_11:02.xlsx']
    fl_path = 'D:\BusinessProject\结果文件\2023-12-01\2023-11-29-2023-11-29-官方旗舰店--2023-12-01_10:57.xlsx'

    # result_dict = compress_pack_file(z_p, "file", file_path_list=f_l)  # 压缩打包文件
    result_dict = compress_pack_file(z_p, "folder", folder_path=fl_path)  # 压缩打包文件夹
    print(result_dict)

实现查找文件夹的文件路径代码

import os


file_paths = []
f_path = r"D:BusinessProject结果文件2023-12-01"
for root, dirs, files in os.walk(f_path):
    for file_name in files:
        file_path = os.path.join(root, file_name)
        file_paths.append(file_path)

print(file_paths)

原文地址:https://blog.csdn.net/gongzairen/article/details/134734026

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_35972.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注