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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
| import os import shutil import zipfile import rarfile
parent_path = input('请输入要解压的文件路径:')
file_flag = '.' + input('请输入一种需要解压的压缩类型(例:zip或rar)解压后会删除原有压缩文件,请注意备份:')
def del_old_zip(file_path): os.remove(file_path)
def zip_decompress(file_path, root): z = zipfile.ZipFile(f'{file_path}', 'r') z.extractall(path=f"{root}") for names in z.namelist(): if names.endswith(file_flag): z.close() return 1 z.close() return 0 def rar_decompress(file_path, root): z = rarfile.RarFile(f'{file_path}', 'r') z.extractall(path=f"{root}") for names in z.namelist(): if names.endswith(file_flag): z.close() return 1 z.close() return 0 decompress = None if file_flag == '.zip': decompress = zip_decompress elif file_flag == '.rar': decompress = rar_decompress else: print('格式输入错误或不支持当前格式') os.system('pause') exit(0)
def start_dir_make(root, dirname): os.chdir(root) os.mkdir(dirname) return os.path.join(root, dirname)
def rem_dir_extra(root, father_dir_name): try: for item in os.listdir(os.path.join(root, father_dir_name)): if not os.path.isdir(os.path.join(root, father_dir_name, item)): continue if item == father_dir_name and len( os.listdir(os.path.join(root, father_dir_name))) == 1: os.chdir(root) os.rename(father_dir_name, father_dir_name + '-old') shutil.move(os.path.join(root, father_dir_name + '-old', item), os.path.join(root)) os.rmdir(os.path.join(root, father_dir_name + '-old')) rem_dir_extra(root, item) else: rem_dir_extra(os.path.join(root, father_dir_name), item) except Exception as e: print("清除文件夹出错" + str(e))
if __name__ == '__main__': flag = 1 while flag: for root, dirs, files in os.walk(parent_path): for name in files: if name.endswith(file_flag): new_ws = start_dir_make(root, name.replace(file_flag, '')) zip_path = os.path.join(root, name) flag = decompress(zip_path, new_ws) del_old_zip(zip_path) rem_dir_extra(root, name.replace(file_flag, '')) print(f'{root}\\{name}'.join(['文件:', '\n解压完成\n'])) rem_dir_extra(os.path.split(parent_path)[0], os.path.split(parent_path)[1]) print("解压完成啦,记得检查有没有{}格式之外的呀!\n\n其他格式需要自己改一下了".format(file_flag)) os.system('pause')
|