栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python 实现多种压缩格式文件解压(zip、7z、rar)带密码解压缩,安装避坑

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python 实现多种压缩格式文件解压(zip、7z、rar)带密码解压缩,安装避坑

代码功能

Python 代码实现对多种压缩格式的文件,进行带密码解压缩,包括RAR格式、7Z格式、ZIP格式带密码解压缩。

环境
系统:ubuntu16.04
Python:3.6.9

程序代码
import os
import zipfile
import py7zr
import rarfile


class UnCompress:
    def __init__(self, file_path, output_path, password=None):
        self.file_path = file_path                  # 输入文件路径
        self.output_path = output_path              # 输出文件路径
        self.password = password                    # 压缩密码

    # zip解压缩
    def unzip_file(self):
        try:
            with zipfile.ZipFile(file=self.file_path, mode='r') as fp:
                fp.extractall(self.output_path, pwd=self.password.encode('ascii'))
            return True
        except:
            return False

    # 7z解压缩
    def un7z_file(self):
        try:
            with py7zr.SevenZipFile(self.file_path, 'r', password=self.password) as fp:
                fp.extractall(path=self.output_path)
            return True
        except:
            return False

    # RAR解压缩
    def unrar_file(self):
        try:
            with rarfile.RarFile(self.file_path, 'r') as fp:
                fp.extractall(self.output_path, pwd=self.password)
            return True
        except:
            return False


    def run(self):
        file_state = False
        if not os.path.exists(self.file_path):
            return file_state
        if not os.path.exists(self.output_path):
            os.makedirs(self.output_path)

        # zip解压缩
        if zipfile.is_zipfile(self.file_path):
            file_state = self.unzip_file()

        # 7z解压缩
        if py7zr.is_7zfile(self.file_path):
            file_state = self.un7z_file()

        # RAR解压缩
        if rarfile.is_rarfile(self.file_path):
            file_state = self.unrar_file()

        return file_state
避坑(linux下rar程序安装)

在linux环境中,不仅需要使用pip安装rarfile,还需要在系统环境中安装rar程序,不然提示错误:
“rarfile.RarCannotExec: Cannot find working tool.”

pip安装
# 安装rarfile
pip install rarfile
安装rar程序

1、下载rar包,去官网进行下载,找到自己需要的程序包,
我下载的是linux 64位程序

2、将程序包放到linux中,进行解压缩

tar -xzvf rarlinux-x64-5.9.1.tar.gz

3、安装

# 进入到解压后的文件夹
cd rar
make
make install
# 若提示没有权限,命令前面加sudo
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/987207.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号