管理网站制作seo免费推广
因为某个需求,需要用python处理解压文件,这里记录下完成的代码,需要注意的是删除解压出来的文件夹时,很多博客都说直接用removedirs就行,实际我在py3.7上测试会提示“文件夹非空”,而且想想如果直接移除了根目录还是很恐怖的,所以我这边做的处理是用MD5作为解压文件夹名称,然后删除的时候判断文件路径长度至少在32以上才执行删除
"""
用于处理文件解压缩以及删除操作
"""
import hashlib
import os
import tarfile
import zipfile
import shutilclass PackProcessor:"""用于处理文件压缩,解压缩以及删除的操作"""unzip_path = ""def __init__(self):"""初始化"""@staticmethoddef compute_md5(fpath: str):"""计算压缩文件的md5值"""with open(fpath, 'rb') as f:md5_hash = hashlib.md5()for chunk in iter(lambda: f.read(4096), b""):md5_hash.update(chunk)hex_digest = md5_hash.hexdigest()return hex_digest@staticmethoddef unzip(fpath: str):"""解压缩文件"""unzip_dir = Nonetry:file_md5 = PackProcessor.compute_md5(fpath)local_dir = os.path.dirname(fpath)unzip_dir = os.path.join(local_dir, file_md5)PackProcessor.unzip_path = unzip_dirif fpath.endswith(".tar.gz"):with tarfile.open(fpath, 'r') as tar:tar.extractall(unzip_dir)elif fpath.endswith(".whl") or fpath.endswith(".egg") or \fpath.endswith(".zip"):with zipfile.ZipFile(fpath, 'r') as zip_file:zip_file.extractall(unzip_dir)else:print("是暂不支持解压的文件")return Noneexcept Exception as e:print("解压失败", e)return unzip_dir@staticmethoddef delete_unzips():"""删除解压出来的文件"""if os.path.exists(PackProcessor.unzip_path) and len(PackProcessor.unzip_path) >= 32:# 直接删除文件夹太危险,防止异常情况直接删除根目录try:shutil.rmtree(PackProcessor.unzip_path)except Exception as e:print("尝试删除失败:", PackProcessor.unzip_path, e)@staticmethoddef get_dir_files(data_dir: str, file_type=''):"""获取指定文件夹下所有指定字符串结尾文件的全路径,返回一个列表"""result_ls = []for path, _, filelist in os.walk(data_dir):for filename in filelist:if filename.endswith(file_type):final_path = os.path.join(path, filename)final_path = final_path.replace('\\', '/')# 统一换成/结尾result_ls.append(final_path)return result_lsif __name__ == '__main__':pass