fyqq0403
 1 \'\'\' 解压一个.zip文件或一个目录下的所有.zip文件到指定目录。
 2     
 3     运行方法: 
 4     格式:
 5         python unzip.py "source_dir" "dest_dir" password
 6     参数说明:
 7         source_dir和dest_dir既可以绝对路径也可以为相对路径。用""将它们括起为了防止路径中出现空格。
 8         source_dir和dest_dir的缺省值表示当前目录。
 9         password缺省表示压缩文件未加密。
10     注意:
11         1. 若目录太长,可以将上述语句直接写入.bat脚本,然后运行脚本。
12         2. 密码的编码格式为“utf-8”,且不支持WinRAR中zip格式的默认加密算法--CBC模式下的AES-256。
13            若想要WinRAR加密压缩的.zip文件能用本程序顺利解压,请在加密压缩时勾选“ZIP传统加密”。     
14 \'\'\'
15 
16 import sys, os, zipfile
17 
18 def unzip_single(src_file, dest_dir, password):
19     \'\'\' 解压单个文件到目标文件夹。
20     \'\'\'
21     if password:
22         password = password.encode()
23     zf = zipfile.ZipFile(src_file)
24     try:
25         zf.extractall(path=dest_dir, pwd=password)
26     except RuntimeError as e:
27         print(e)
28     zf.close()
29 
30 def unzip_all(source_dir, dest_dir, password):
31     if not os.path.isdir(source_dir):    # 如果是单一文件
32         unzip_single(source_dir, dest_dir, password)
33     else:
34         it = os.scandir(source_dir)
35         for entry in it:
36             if entry.is_file() and os.path.splitext(entry.name)[1]==\'.zip\' :
37                 unzip_single(entry.path, dest_dir, password)
38     
39 if __name__ == "__main__":
40     
41     # 获取源路径和目标路径
42     source_dir = os.getcwd()
43     dest_dir = os.getcwd()
44     password = None
45     if len(sys.argv) == 2: # 指定了压缩文件所在路径
46         source_dir = sys.argv[1]
47     if len(sys.argv) == 3: # 压缩文件所在和解压到路径均指定
48         source_dir, dest_dir = os.path.abspath(sys.argv[1].strip(\'"\')), os.path.abspath(sys.argv[2].strip(\'"\'))
49     if len(sys.argv) == 4: # 还指定了密码
50         source_dir, dest_dir, password =  os.path.abspath(sys.argv[1].strip(\'"\')), os.path.abspath(sys.argv[2].strip(\'"\')), sys.argv[3]
51     if len(sys.argv) > 4:
52         print(\'过多的参数,可能是路径中有空白字符,请用""将路径括起。\')
53         exit()
54     
55     print("源目录:", source_dir)
56     print("解压到:", dest_dir)
57     print("解压密码:", password)
58     
59     # 判断源路径是否合法
60     if not os.path.exists(source_dir):
61         print("压缩文件或压缩文件所在路径不存在!")
62         exit()
63     if not os.path.isdir(source_dir) and not zipfile.is_zipfile(source_dir):
64         print("指定的源文件不是一个合法的.zip文件!")
65         exit()
66     
67     # 如果解压到的路径不存在,则创建     
68     if not os.path.exists(dest_dir):
69         os.mkdir(dest_dir)
70     
71     unzip_all(source_dir, dest_dir, password)

 

分类:

技术点:

相关文章: