跳过正文
  1. Teches/
  2. 程序语言/
  3. python/
  4. 程序功能/

压缩解压

·99 字·1 分钟
目录

解压
#

基础
#

解压zip
模块:zipfile

</> python
1import zipfile
2with zipfile.ZipFile(fp, 'r') as zip_ref:
3    zip_ref.extractall()

递归解压zip
#

模块:zipfile, pathlib
zipfile.ZipFile.extract(fi, ep)方法逐个判断fi.filename是否匹配zip文件,匹配则进入递归解压

</> python
 1import zipfile
 2from pathlib import Path
 3from os.path import join
 4def r_unzip(fp:Path, ep:str='./unzip') -> int:
 5    # 统计解压的zip文件数
 6    c = 1
 7    try:
 8        extr_path = join(ep, fp.stem.split('.zip')[0])
 9        with zipfile.ZipFile(fp, 'r') as zip_ref:
10            for finfo in zip_ref.infolist():
11                zip_ref.extract(finfo, extr_path)
12                extr_file = Path(join(extr_path, finfo.filename))
13                if extr_file.match("*.zip"):
14                    c += r_unzip(extr_file, extr_path)
15    except Exception as e:
16        print(f'file error, pass:{fp}, error msg:{e}')
17    finally:
18        return c