使用python解压rar和zip压缩包(windows)

1. 环境配置

  • 解压rar文件需要下载一些本地依赖

  • 解压zip文件可能遇到乱码问题,在zipfile模块中把编码部分修改下即可

  • 具体方法可在网络找到。

2. python脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import os,zipfile
from unrar import rarfile
root_path = os.path.abspath('./')
print(root_path)

def unrar_file(rar_src,dst_dir):
rf = rarfile.RarFile(rar_src)
rf.extractall(dst_dir)

def unzip_file(zip_src, dst_dir):
'''
解压缩
'''
r = zipfile.is_zipfile(zip_src)
if r:
fz = zipfile.ZipFile(zip_src, 'r')
for file in fz.namelist():
fz.extract(file, dst_dir)
else:
print('This is not zip')
return False
return True

path = './'
res = os.walk(path)

path = root_path
res = os.listdir(path)
num = 0
for file in res:
if os.path.isdir(file):
num += 1
stu_path = os.path.join(root_path,file)
for stu_file in os.listdir(stu_path):
if len(stu_file)>4 and stu_file[-4:] == '.zip':
try:
print(stu_file)
zip_src = os.path.join(stu_path,stu_file)
unzip_file(zip_src,stu_path)
except Exception as e:
print("can not unzip ",stu_file)
print(e)
if len(stu_file)>4 and stu_file[-4:] == '.rar':
try:
print(stu_file)
rar_src = os.path.join(stu_path,stu_file)
unrar_file(rar_src,stu_path)
except Exception as e:
print("can not unrar ",stu_file)
print(e)
print('学生数量:',num)