1. 程式人生 > >Python解壓.zip文件

Python解壓.zip文件

err spl close enc get strip 寫入 split 支持

 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)

Python解壓.zip文件