代码功能
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