博客
关于我
Python tarfile、zipfile解压模块讲解
阅读量:798 次
发布时间:2023-03-06

本文共 533 字,大约阅读时间需要 1 分钟。

import tarfileimport zipfile# 读取文件扩展名以确定解压缩工具ext = filename.split('.')[-1]if ext == '.zip':    # 使用ZipFile对象进行读取    fp = zipfile.ZipFile(filename, 'r')elif ext in ('.tar', '.gz'):    # 使用tarfile对象进行只读解压    fp = tarfile.open(filename, 'r')else:    # 处理不支持的文件类型    raise AssertionError('仅支持.zip、.tar和.gz文件类型')# 解压指定目录的所有内容fp.extractall(target_dir)
  • 首先读取文件扩展名,以确定使用合适的解压缩工具。这种方法确保了代码的灵活性和适用性。

  • 对于ZIP文件,使用zipfile模块进行读取操作。对于TAR和GZ文件,则使用tarfile模块以只读模式打开文件。

  • 代码中使用了异常处理,确保在检测到非法文件类型时能够及时报错,保证程序的安全性和可靠性。

  • 最后,调用extractall方法进行解压操作,指定目标目录以便组织文件结构。

  • 转载地址:http://ceafk.baihongyu.com/

    你可能感兴趣的文章
    python | h5py,一个无敌的关于 HDF5 的 Python 库!
    查看>>
    python | huey,一个非常厉害的 任务调度 Python 库!
    查看>>
    python | hypothesis,一个有趣的 Python 库!
    查看>>
    python | Indico,一个超酷的 Python 库!
    查看>>
    python | isort,一个有趣的 自动整理导入语句 的Python 库!
    查看>>
    python | jinja,一个超酷的 Python 库!
    查看>>
    python | joblib,一个强大的 Python 库!
    查看>>
    python调用git bash_Python学习第70课-用Git Bash在命令行打开sublime
    查看>>
    python | jsonschema,一个实用的 验证 JSON 数据结构 Python 库!
    查看>>
    python课程的中期报告范文_课题研究中期总结报告范文
    查看>>
    python | lxml,一个超酷的 关于XML/HTML 文档 Python 库!
    查看>>
    python | mplfinance,一个有趣的金融数据可视化 Python 库!
    查看>>
    python | nipy,一个强大的关于 神经影像数据分析 的Python 库!
    查看>>
    python | NLTK,一个强大的 自然语言处理 Python 库!
    查看>>
    python | nupic,一个强大的 处理时间序列的Python 库!
    查看>>
    python | orange3,一个神奇的 Python 库!
    查看>>
    python | pdfminer,一个神奇的 关于PDF 文件的 Python 库!
    查看>>