while to_extract: file_path = to_extract.pop(0) if file_path in extracted: continue # 记录当前压缩包的名字 compressed_files.append(file_path) extracted.add(file_path) file_extension = os.path.splitext(file_path)[1].lower()
if file_extension == '.zip': # 解压zip文件 try: with zipfile.ZipFile(file_path, 'r') as zip_ref: zip_ref.extractall(os.path.dirname(file_path)) except zipfile.BadZipFile: print(f"文件 {file_path} 不是有效的 ZIP 文件或已损坏。") elif file_extension == '.7z': # 解压7z文件 try: with py7zr.SevenZipFile(file_path, mode='r') as z: z.extractall(os.path.dirname(file_path)) except py7zr.Bad7zFile: print(f"文件 {file_path} 不是有效的 7z 文件或已损坏。") elif file_extension in ['.tar', '.tar.gz', '.tar.bz2']: # 解压tar文件 try: with tarfile.open(file_path, 'r') as tar_ref: tar_ref.extractall(os.path.dirname(file_path), filter='data') except tarfile.ReadError: print(f"文件 {file_path} 不是有效的 tar 文件或已损坏。") else: print(f"不支持的文件格式: {file_path}") continue
# 查找新生成的压缩包并添加到待解压队列 for root, dirs, files in os.walk(os.path.dirname(file_path)): for file in files: new_file_path = os.path.join(root, file) new_extension = os.path.splitext(new_file_path)[1].lower() if new_extension in ['.zip', '.7z', '.tar', '.tar.gz', '.tar.bz2']: to_extract.append(new_file_path)
if __name__ == "__main__": # 输入要解压的压缩包路径 archive_path = input("请输入压缩包的路径: ") if os.path.exists(archive_path): extract_archive(archive_path) print("每层压缩包的名字:") for file in compressed_files: print(file) else: print("输入的路径不存在,请检查后重新输入。")