有些时候,我们需要解压多个压缩包,而使用压缩工具,只能一个一个的操作,十分浪费时间,这篇博客中,我使用了python书写了一个代码,能够对一个文件夹下的多个tar格式的压缩包进行解压,同时以压缩包的名字保存压缩内容,并删除压缩包以节约空间。
import os import tarfile def extract_to_named_folders_and_delete(directory): # 遍历指定目录下的所有文件 for entry in os.listdir(directory): # 构建文件的完整路径 full_path = os.path.join(directory, entry) # 确认文件是tar文件 if os.path.isfile(full_path) and full_path.endswith('.tar'): # 解压前创建以tar文件名命名的文件夹 extract_folder = os.path.join(directory, os.path.splitext(entry)[0]) os.makedirs(extract_folder, exist_ok=True) # 打开并解压tar文件 with tarfile.open(full_path, 'r') as tar: tar.extractall(path=extract_folder) # 删除压缩包 os.remove(full_path) print(f"Extracted to {extract_folder} and removed {full_path}") # 指定需要处理的文件夹路径 your_directory = 'G:/ILSVRC2012_img_train' extract_to_named_folders_and_delete(your_directory)标签:解压,full,tar,os,path,extract,压缩包 From: https://blog.csdn.net/qq_45906596/article/details/139674777