python批量处理压缩文件

时间:2023-11-16 11:58:02

python批量处理压缩文件

博客小序:在数据的处理中,下载的数据很有可能是许多个压缩文件,自己一个一个解压较为麻烦,最近几日自己在处理一次下载的数据时,遇到大量的压缩数据需要处理,于是利用python进行了处理,特撰此博文以记之。

参考博客:

https://blog.****.net/qq_38697681/article/details/79424259

https://blog.****.net/brucewong0516/article/details/79064384

1.脚本处理情况说明

本实例中,需要处理的压缩数据是分省的数据,每个省由若干数量不同的压缩包构成,数据具体情况见截图,本脚本主要的任务有两个:

1.将压缩文件中需要的(xxxxxdem.tif)数据解压提取出来

2.将提取出来的数据仍按照省份进行存储

python批量处理压缩文件

python批量处理压缩文件

python批量处理压缩文件

python批量处理压缩文件

2.脚本代码

#添加一个计时器
import time
start = time.time() import os
import shutil
import glob
import zipfile def un_zip(all_o_files,new_folder_dir,key_words): # 读取原文件夹下的压缩文件
for i in all_o_files: new_file = new_folder_dir + "\\" + os.path.basename(i)
if os.path.exists(new_file):
shutil.rmtree(new_file)
os.mkdir(new_file)
else:
os.mkdir(new_file) all_zip_files = glob.glob(i + "\\*.zip") # 对于每个压缩文件
for z in all_zip_files:
# 对没有损毁的压缩包进行解压
try:
zip_data = zipfile.ZipFile(z)
a_name = zip_data.namelist() for name in a_name:
if (name.find(key_words)) > -1:
try:
zip_data.extract(name, new_file)
except:
print(z + "解压失败")
pass
print(z + "解压完成!!!!!!!!") zip_data.close()
except:
bad_file.append(z)
print(z + "文件已损毁") tif_file = glob.glob(new_file + "\\" + "*")
for file in tif_file:
tif_datas = glob.glob(file + "\\"+ "*.tif")
for tif_data in tif_datas:
shutil.move(tif_data, new_file) shutil.rmtree(file) o_folder_dir = "D:\\cnblogs\\data\\china"
all_o_files = glob.glob(o_folder_dir + "\\*") #选择新文件存储的位置,如果在源文件的目录下则不要自己手动创建,
new_folder_dir = "D:\\cnblogs\\data\\china_unzip"
if os.path.exists(new_folder_dir):
shutil.rmtree(new_folder_dir)
os.mkdir(new_folder_dir)
else:
os.mkdir(new_folder_dir) bad_file = [] #需要解压的出来的文件名称中通有的名字特征,最好是名称结尾的,如.tif等表示文件类型的
key_words = "dem.tif" un_zip(all_o_files,new_folder_dir,key_words) print("全部解压完毕!!!!!!!")
print("损毁的压缩文件包括如下:")
print(bad_file) end = time.time()
print ("程序运行时间{:.2f}分钟".format((end-start)/60.0))

3.问题总结

1.由于开始时没有考虑压缩文件存在损毁的情况,所以第一次写出来的脚本存在一定的问题,也提醒自己要注意脚本编写过程中可能遇到的异常情况,适当的使用try,except来捕获可能出现的问题

2.本代码只考虑了.zip类型的压缩文件,还有其他形式的压缩文件暂未考虑,未来有机会遇到再补充。


本文作者:DQTDQT

限于作者水平有限,如文中存在任何错误,欢迎不吝指正、交流。

联系方式:

QQ:1426097423

E-mail:duanquntaoyx@163.com

本文版权归作者和博客园共有,欢迎转载、交流,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,如果觉得本文对您有益,欢迎点赞、探讨。