python解压rar格式文件,需要安装rarfile模块,去网上下载rarfile,我这里下载的是rarfile-2.4.tar.gz,解压还需要对应的UnRAR.exe
将rarfile-2.4.tar.gz拷贝到python安装路径的Scripts目录下:
cmd进入到python的Scripts目录下运行pip install rarfile-2.4.tar.gz,安装成功如下图:
import os
import rarfile
base_path = r'F:\python\rar'
def unrar(base_path):
files = os.listdir(base_path)
files.sort()
for path in files:
full_path = os.path.join(base_path, path)
print(full_path)
z = rarfile.RarFile(full_path)
z.extractall(base_path)
z.close()
os.remove(full_path)
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)
def main():
unrar(base_path)
rar(base_path)
if __name__ == "__main__":
main()
【注意】:
需要将UnRAR.exe文件放到和python脚本统计目录下,否则虽然脚本运行成功,但是不会生成解压后的文件