实现一个批量解压缩并去重的功能

python 复制代码
import os
import zipfile
import tarfile
import gzip
import hashlib
import pandas as pd

def get_file_list(dir_path):
    """获取指定目录下的所有文件列表"""
    file_list = []
    for root, dirs, files in os.walk(dir_path):
        for file in files:
            file_path = os.path.join(root, file)
            file_list.append(file_path)
    return file_list

def get_file_suffix(file_path):
    """获取文件的后缀名"""
    file_name, file_suffix = os.path.splitext(file_path)
    return file_suffix

def get_md5(file_path):
    """获取文件的 MD5 校验值"""
    md5 = hashlib.md5()
    with open(file_path, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            md5.update(chunk)
    return md5.hexdigest()

def unzip(file_path, target_dir):
    """解压缩文件"""
    suffix = get_file_suffix(file_path)
    if suffix == ".zip":
        return zipfile.ZipFile(file_path).extractall(target_dir)
    elif suffix == ".tar":
        return tarfile.open(file_path, "r:gz").extractall(target_dir)
    elif suffix == ".7z":
        return 7zfile.open(file_path, "r").extractall(target_dir)
    elif suffix == ".gz":
        with gzip.open(file_path, "rb") as f:
            return f.read().decode("utf-8")
    else:
        raise Exception(f"不支持的文件格式:{suffix}")

def is_duplicate(file_path, file_map):
    """判断文件是否重复"""
    file_size = os.path.getsize(file_path)
    file_mtime = os.path.getmtime(file_path)
    if file_path in file_map:
        if file_map[file_path]["size"] == file_size and file_map[file_path]["mtime"] == file_mtime:
            return True
    else:
        file_map[file_path] = {"size": file_size, "mtime": file_mtime}
        return False

def main():
    """主函数"""
    # 获取输入参数
    cur_dir = os.getcwd()
    input_dir = input("请输入需要解压缩的文件存放目录:")
    output_dir = input("请输入解压缩后的存放目录:")
    # 获取文件列表
    file_list = get_file_list(input_dir)
    # 创建解压缩后的存放目录
    if not os.path.exists(output_dir):
        os.mkdir(output_dir)
    # 解压缩文件
    progress_bar = ProgressBar(len(file_list))
    file_map = {}
    for file_path in file_list:
        file_path = os.path.join(input_dir, file_path)
        unzip(file_path, output_dir)
        progress_bar.update()
    # 去重复文件
    for file_path in os.listdir(output_dir):
        file_path = os.path.join(output_dir, file_path)
        if is_duplicate(file_path, file_map):
            os.remove(file_path)

class ProgressBar:
    """进度条类"""
    def __init__(self, total):
        self.total = total
        self.progress = 0

    def update(self):
        self.progress += 1
        sys.stdout.write("\r%.2f%%" % (self.progress / self.total * 100))
        sys.stdout.flush()

    @property
    def finished(self):
        return self.progress >= self.total

if __name__ == "__main__":
    main()

注意:在运行上述代码之前,您需要确保已经安装了所有必要的库,如pandas、zipfile、tarfile、gzip等。您可以使用以下命令来安装这些库:

pip install pandas zipfile tarfile gzip

此外,由于您的代码中使用了7zfile,但这个库在Python的标准库中不存在,您需要使用第三方库来处理.7z文件。您可以使用py7zr库,它是7z文件的一个Python实现。您可以使用以下命令来安装py7zr:

pip install py7zr

相关推荐
菜包eo6 分钟前
二维码驱动的独立站视频集成方案
网络·python·音视频
Yo_Becky12 分钟前
【PyTorch】PyTorch预训练模型缓存位置迁移,也可拓展应用于其他文件的迁移
人工智能·pytorch·经验分享·笔记·python·程序人生·其他
yzx99101324 分钟前
关于网络协议
网络·人工智能·python·网络协议
fangeqin25 分钟前
ubuntu源码安装python3.13遇到Could not build the ssl module!解决方法
linux·python·ubuntu·openssl
csdn_aspnet1 小时前
在 Windows 机器上安装和配置 RabbitMQ
windows·rabbitmq
Jay Kay1 小时前
TensorFlow源码深度阅读指南
人工智能·python·tensorflow
会的全对٩(ˊᗜˋ*)و1 小时前
【数据挖掘】数据挖掘综合案例—银行精准营销
人工智能·经验分享·python·数据挖掘
csdn_aspnet2 小时前
Windows Server 上的 RabbitMQ 安装和配置
windows·rabbitmq
___波子 Pro Max.2 小时前
GitHub Actions配置python flake8和black
python·black·flake8
阿蒙Amon3 小时前
【Python小工具】使用 OpenCV 获取视频时长的详细指南
python·opencv·音视频