Python实现rar、zip和7z文件的压缩和解压

Python实现rar、zip和7z文件的压缩和解压

一、7z压缩文件的压缩和解压

1、安装py7zr

我们要先安装py7zr第三方库:

pip install py7zr

如果python环境有问题,执行上面那一条安装语句老是安装在默认的python环境的话,我们可以执行下面这条语句,将第三方库安装在项目的虚拟环境中:

pip install py7zr --target=E:\Python脚本\作业查重\OS_Study\venv\Lib\site-packages

2、解压7z文件

import py7zr

# 将压缩文件解压到指定目录

def decompress_7z():

# 将要解压的压缩文件路径

archive = py7zr.SevenZipFile(r'E:\Python脚本\作业查重\20大数据班Javaweb新闻系统.7z', mode='r')

# 压缩文件的解压目录

archive.extractall(path=r'E:\Python脚本\作业查重\20大数据班Javaweb新闻系统')

archive.close()

3、压缩成7z文件

import py7zr

# 将指定目录压缩到指定压缩文件test.7z'

def compression_7z():

# 生成的压缩文件路径

archive = py7zr.SevenZipFile(r'E:\Python脚本\作业查重\test.7z', mode='w')

# 需要压缩的压缩文件

archive.writeall(path=r'../test')

archive.close()

二、rar压缩文件的压缩和解压

1、环境准备

我们用到的第三方库为rarfile,因为我们的这个第三方库需要用到第三方程序,所以我们要先配一下环境。

(1)导入unrar模块:

pip install unrar

(2)下载 unrar library 并按照默认安装路径安装,下载链接:下载

(3) 编辑环境变量:

用户变量 -> 变量名:x64 -> 变量值:C:\Program Files (x86)\UnrarDLL\x64 (默认路径是这个) 系统变量 -> 变量名:UNRAR_LIB_PATH -> 变量值:C:\Program Files (x86)\UnrarDLL\x64\UnRAR64.dll (默认路径)[32位系统下的变量值为C:\Program Files (x86)\UnrarDLL\UnRAR.dll]

(4)安装winrar(360软件中心有): 将 winrar 的目录下的 unrar.exe 复制到 Python 路径的 Scripts 文件夹下。 (5)重启Pycharm

2、安装rarfile

执行以下命令:

pip install rarfile

3、解压rar文件

import rarfile

def decompress_rar():

# 找到rar文件

z = rarfile.RarFile(r'E:\Python脚本\作业查重\2015090103石凯-新闻管理系统.rar')

# 指定解压输出的目录

z.extractall(r'E:\Python脚本\作业查重\2015090103石凯-新闻管理系统')

z.close()

# 删除压缩文件

# os.remove(pathRar)

4、压缩成rar文件

由于rarfile只能解压文件不能压缩文件,所以我们需要调用第三方程序来完成。

def compress(input_file, output_file, root_path,

rar_path='D:/"Program Files"/WinRAR/WinRAR.exe'):

"""

调用CMD命令压缩文件/文件夹

Parameters

----------

input_file : 需要压缩的文件/文件夹名。从哪一级目录开始,就会从哪一级开始压缩;

output_file : 压缩文件的输出路径及其压缩的文件名;

可以是.rar, .zip;

root_path: input_file 所在目录;

rar_path : WinRAR软件的安装路径,

The default is 'C:/"Program Files"/WinRAR/WinRAR.exe'.

NOTE: 路径和文件名中带空格的时候一定要多加一重引号!!

"""

cmd_command = r'%s a %s %s' % (rar_path, output_file, input_file)

print(root_path)

os.chdir(root_path) # 切换工作目录

print(cmd_command)

os.system(cmd_command)

if os.system(cmd_command)==0:

print('Successful backup to', output_file)

else:

print('Backup FAILED', input_file)

def rar(paths):

files = os.listdir(paths)

for path in files:

input_file = '"' + path + '"'

out = path.split('.')[0] + '_bak.rar'

out_file = '"' + out + '"'

print(path)

print(out)

compress(input_file,out_file,paths)

参考文章:https://blog.csdn.net/hanmengaidudu/article/details/120193682

三、zip文件的压缩和解压

1、安装zipfile

执行以下命令:

pip install zipfile

2、解压zip文件

使用zipfile的extract()或extractall()方法直接解压时,文件名可能会出现乱码,所以我们要特别解决这个问题:

# 出现乱码时解码

def recode(raw: str) -> str:

try:

return raw.encode('cp437').decode('gbk')

except:

return raw.encode('utf-8').decode('utf-8')

# 解压zip文件

def decompress_zip(pathZip, obj):

zipFile = zipfile.ZipFile(pathZip) # 压缩包路径

zipFileList = zipFile.namelist() # 获取压缩包里所有文件

print('-------------------正在解压-----------------------')

for f in zipFileList:

zipFile.extract(f, obj) # 循环解压文件到指定目录

name1 = os.path.join(obj, f) # 乱码文件名

name2 = os.path.join(obj, recode(f)) # 解码后文件名

os.rename(name1, name2) # 文件重命名

zipFile.close() # 关闭文件释放内存

print('-------------------解压完成-----------------------')

# 删除压缩文件

# os.remove(pathZip)

3、压缩成zip文件

参考文章:https://blog.csdn.net/Likianta/article/details/126710855

参考文章:https://blog.csdn.net/ooowwq/article/details/125949394

参考 文章:https://blog.csdn.net/qq_36182112/article/details/127630950

四、批量解压

如果想要实现批量解压某个目录下的全部压缩包的话,可以配合python自带的od库来实现,一些参考代码如下:

# 批量解压文件

def batch_decompress():

file_names = os.listdir(r'E:\Python脚本\作业查重\20大数据班Javaweb新闻系统') # 压缩文件所在的目录

# print(file_names)

print('-------------------正在解压-----------------------')

for file_name in file_names:

# 将文件名与目录拼接起来,得到文件绝对路径地址

path_name = os.path.join(r'E:\Python脚本\作业查重\20大数据班Javaweb新闻系统', file_name)

print(path_name)

if path_name[path_name.find('.')+1:] == 'zip':

decompress_zip(path_name)

elif path_name[path_name.find('.')+1:] == 'rar':

decompress_rar(path_name)

else:

decompress_7z(path_name)

print('-------------------解压完成-----------------------')

相关推荐

女主播攻略
mobile365-777

女主播攻略

📅 08-31 👁️ 1276
关于稜的成语
365Bet官方

关于稜的成语

📅 10-15 👁️ 481
【时钟塔】修行开启(3.24-4.27)
365bet网上手机投注

【时钟塔】修行开启(3.24-4.27)

📅 09-03 👁️ 4591
哪些车配备了hud抬头显示
mobile365-777

哪些车配备了hud抬头显示

📅 01-18 👁️ 5855
为什么要有架构?
365Bet官方

为什么要有架构?

📅 10-24 👁️ 7309
梦幻西游手游龙宫和魔王伤害哪个更高?
365bet网上手机投注

梦幻西游手游龙宫和魔王伤害哪个更高?

📅 09-03 👁️ 7764
香槟色汽车图片,香槟色汽车优缺点
365bet网上手机投注

香槟色汽车图片,香槟色汽车优缺点

📅 01-01 👁️ 3450