以下代碼為解壓zip包 tar包文件
zip_path:文件絕對路徑
output_folder:文件解壓后存放的文件夾路徑
def extract_file(zip_path, output_folder):# 支持解壓zip tar tar.gz tar.xz .tar.bz2# 確保輸出文件夾存在os.makedirs(output_folder, exist_ok=True)# 解壓文件if zip_path.endswith('.zip'):with zipfile.ZipFile(zip_path, 'r') as zip_ref:zip_ref.extractall(output_folder)else:mode = ""if zip_path.endswith('.tar.xz') or zip_path.endswith('.txz'):mode = 'r:xz'elif zip_path.endswith('.tar.gz') or zip_path.endswith('.tgz'):mode = 'r:gz'elif zip_path.endswith('.tar.bz2') or zip_path.endswith('.tbz2'):mode = 'r:bz2'elif zip_path.endswith('.tar'):mode = 'r:'else:raise ValueError("文件格式暫不支持")if mode:with tarfile.open(zip_path, mode) as tar:tar.extractall(path=output_folder)print(f"文件{os.path.basename(zip_path)}已成功解壓到 {output_folder}")