PYTHON解压tar、zip

it2024-07-06  44

1、解压tar、删除文件 import os,sys import zipfile import tarfile input_path=os.getcwd()+'\\inputfile\\' output_path=os.getcwd()+'\\inputfile\\' os.chdir(input_path) def dc(files,file_path,output_path): os.getcwd()#当前路径 os.chdir(file_path)#转到路径 for file_name in files: print(file_name) tar=tarfile.open(file_name,"r:gz") names = tar.getnames() for name in names: print(name) tar.extract(name,input_path) tar.closed def files_save(input_path): for file_path,sub_dirs,files in os.walk(input_path):#获取所有文件名,路径 print(file_path,sub_dirs,files) dc(files,file_path,output_path) def del_file(path): ls = os.listdir(path) for i in ls: if (i[-6:])=='tar.gz': c_path = os.path.join(path, i) if os.path.isdir(c_path): del_file(c_path) print(c_path) else: os.remove(c_path) print(c_path) files_save(input_path) del_file(input_path) 2、解压删除zip文件 import os,sys import zipfile input_path=os.getcwd()+'\\inputfile\\' output_path=os.getcwd()+'\\inputfile\\' os.chdir(input_path) def dc(files,file_path,output_path): os.getcwd()#当前路径 os.chdir(file_path)#转到路径 for file_name in files: print(file_name) r = zipfile.is_zipfile(file_name)#判断是否解压文件 if r: zpfd = zipfile.ZipFile(file_name)#读取压缩文件 zpfd.extractall() #os.chdir(output_path)#转到存储路径 #zpfd.extractall() #zpfd.close() def files_save(input_path): for file_path,sub_dirs,files in os.walk(input_path):#获取所有文件名,路径 print(file_path,sub_dirs,files) dc(files,file_path,output_path) def del_file(path): ls = os.listdir(path) for i in ls: if (i[-3:])=='zip': c_path = os.path.join(path, i) if os.path.isdir(c_path): del_file(c_path) print(c_path) else: os.remove(c_path) print(c_path) files_save(input_path) del_file(input_path) 3、删除文件 import os,sys import zipfile input_path=os.getcwd()+'\\inputfile\\' output_path=os.getcwd()+'\\inputfile\\' os.chdir(input_path) def del_file(path): ls = os.listdir(path) for i in ls: if (i[-3:])=='xml': c_path = os.path.join(path, i) if os.path.isdir(c_path): del_file(c_path) print(c_path) else: os.remove(c_path) print(c_path) del_file(input_path)
最新回复(0)