批量文件解压缩脚本(Python3.5 + WinRAR)

 1import os  
 2
 3s = os.sep
 4
 5#全局变量
 6List_Err = []
 7
 8#dirroot = "D:" + s + "实验报告" + s        #要遍历的目录
 9currentdir = os.path.abspath('.')          #遍历当前目录
10
11#print(currentdir)
12
13#文件名有空格,则重新命名
14for rt, dirs, files in os.walk(currentdir):
15    for f in files:
16        fname = os.path.splitext(f)               
17        if fname[1] == ".rar" or fname[1] == ".zip" or fname[1] == ".7z":             
18            if ' ' in fname[0]:
19                try:
20                    os.rename(currentdir + s + f, currentdir + s + 
21                    fname[0].replace(" ","") + fname[1])  
22                except Exception as e:
23                    print('重命名失败:'+e)
24
25for rt, dirs, files in os.walk(currentdir):    
26    for f in files:
27        fname = os.path.splitext(f)
28               
29        if fname[1] == ".rar" or fname[1] == ".zip" or fname[1] == ".7z":        
30        
31            #方法一:手动解压, 拷贝到cmd下解压       
32            #rar_command ='"C:\\Program Files\\WinRAR\\WinRAR.exe" x %s * %s\\'%(
33            #    currentdir + s + f, currentdir + s + fname[0])   
34             
35            #方法二:自动解压, 要求:文件的路径不能有空格 
36            rar_command ='"C:\\Program Files\\WinRAR\\WinRAR.exe" x %s * %s\\'%(
37                currentdir + s + f, currentdir + s + fname[0]) 
38             
39            #print(rar_command)  
40            if os.system(rar_command) == 0:  
41                print(fname[0] + " == 成功")  
42            else:
43                List_Err.append(fname[0])
44
45if len(List_Err) > 0:
46    print(" ============ 失败名单 ============ ")
47    for file in List_Err:
48        print(file)