python 解压zip rar 7z文件

  • 1、zip等格式文件解压文件
  • 2、删除临时文件
  • 3、shutil添加解压7z格式文件支持
  • 4、rar格式文件解压
    • 利用 winrar 软件进行解压
  • 5、zip和rar文件格式

1、zip等格式文件解压文件

使用shutil,支持的压缩文件格式,一般常用解压格式为.zip文件。

import shutilprint(shutil.unpack_formats())

输出:

[('bztar', ['.tar.bz2', '.tbz2'], "bzip2'ed tar-file"), ('gztar', ['.tar.gz', '.tgz'], "gzip'ed tar-file"), ('tar', ['.tar'], 'uncompressed tar file'), ('xztar', ['.tar.xz', '.txz'], "xz'ed tar-file"), ('zip', ['.zip'], 'ZIP file')]

解压文件

extract_dir = "./tmp/"
shutil.unpack_archive(current_file, extract_dir)

2、删除临时文件

解压文件后需要删除临时文件

import os
os.remove(full_name)

3、shutil添加解压7z格式文件支持

import os
from py7zr import unpack_7zarchive
import shutilif __name__ == "__main__":path = r"E:\Dataset\新建文件夹"suffix = ".zip"  # ".7z"  ".rar"# file_list = GetFiles(path, suffix)# print("there are ", len(file_list), "zip files")# file_list = GetFiles(path, suffix)# print("there are ", len(file_list), "rar files")shutil.register_unpack_format('7zip', ['.7z'], unpack_7zarchive)file_list = GetFiles(path, suffix)print("there are ", len(file_list), "7z files")current_file = file_list[0]print("current file ", current_file)extract_dir = "./tmp/"shutil.unpack_archive(current_file, extract_dir)

4、rar格式文件解压

安装 unrar 模块:

pip install rarfile
pip install unrar

下载 http://www.rarlab.com/rar/UnRARDLL.exe
安装后设置环境变量

测试

(pytorch190) C:\Users\wmz>python
Python 3.8.10 (default, May 19 2021, 13:12:57) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from unrar import rarfile

参考:解决Python下安装unrar后仍然提示Couldn’t find path to unrar library…
如果文件后缀名并不是文件的压缩格式,这就比较麻烦,比如后缀名为.rar的文件实际是.zip压缩格式。
这就需要判断文件的真实压缩格式,然后在做相应的处理。

import gzip
import os
import tarfile
import zipfile
from unrar import rarfiledef decompress_rar(src_file, dest_dir):"""Decompress rar file into destination direction"""rv = (True, '')try:rar = rarfile.RarFile(src_file)rar.extractall(dest_dir)except Exception as e:rv = (False, e)return rvreturn rvdef decompress_tar_and_tgz(src_file, dest_dir):"""Decomporess .tar or .tgz file into destination directory"""rv = (True, '')try:tar = tarfile.open(src_file)names = tar.getnames()for name in names:tar.extract(name, dest_dir)tar.close()except Exception as e:rv = (False, e)return rvreturn rvdef decompress_zip(src_file, dest_dir):"""Decompress .zip file into destination folder"""rv = (True, '')try:zip_file = zipfile.ZipFile(src_file)for name in zip_file.namelist():zip_file.extract(name, dest_dir)zip_file.close()except Exception as e:rv = (False, e)return rvreturn rvdef decompress_gz(src_file, dest_dir):"""Decompress .gz file into destination folder"""rv = (True, "")try:fname = dest_dir + '/' + os.path.basename(src_file)gfile = gzip.GzipFile(src_file)open(fname, "w+").write(gfile.read())gfile.close()except Exception as e:rv = (False, e)return rvreturn rvdef decompress(src_file, dest_dir):fname, ext = os.path.splitext(src_file)if ext in ('.tgz', '.tar'):decompress_tar_and_tgz(src_file, dest_dir)elif ext == '.zip':decompress_zip(src_file, dest_dir)        elif ext == '.rar':decompress_rar(src_file, dest_dir)elif ext == '.gz':decompress_gz(src_file, dest_dir)def decompress_folder(src_dir):files = os.listdir(src_dir)for fname in files: # fname is file name with extensionname, ext = os.path.splitext(fname) # name is file name without extensionsrc_file = os.path.join(src_dir, fname)dest_path = os.path.join(src_dir, name)if not os.path.exists(dest_path):os.mkdir(dest_path)decompress(src_file, dest_path)print(src_file, 'was decompressed.')if __name__ == '__main__':src_dir = r'D:\some_folder_name'decompress_folder(src_dir)

利用 winrar 软件进行解压

winrar 提供命令行解压,Python 语言可以调用 winrar 命令。在执行命令之前,把 winrar.exe 所在的路径加到环境变量。然后,比如,我们要把 D:\test 下所有 zip 文件解压,可以用下面的命令:

winrar.exe x D:\test\*.zip D:\test\unzip\

winrar 的命令行参数很多,这里不展开,x 表示使用绝对路径进行解压。Python 对 winrar 命令进行封装的代码如下:

import osdef unzip_folder(sourcepath):if sourcepath[-1:] == "\\":files = sourcepath + "*.zip"else:files = sourcepath + "\\" + "*.zip"dest = sourcepath + "\\unzip\\"cmd = 'WinRAR.exe x {} {}'.format(files, dest)os.system(cmd)  if __name__ == "__main__":source_folder = r"D:\test\\"unzip_folder(source_folder)

参考:Python解压常见格式的压缩文件

5、zip和rar文件格式

根据文件头判断文件格式

参考:压缩包Zip格式详析(全网最详细)
参考:RAR文件格式学习(了解)

python 解压zip rar 7z文件相关推荐

  1. Android解压zip rar 7z文件

    添加依赖 implementation 'org.apache.commons:commons-compress:1.23.0' implementation 'com.github.junrar:j ...

  2. Python解压zip文件出现TypeError: pwd: expected bytes, got str的解决方案

      大家好,我是爱编程的喵喵.双985硕士毕业,现担任全栈工程师一职,热衷于将数据思维应用到工作与生活中.从事机器学习以及相关的前后端开发工作.曾在阿里云.科大讯飞.CCF等比赛获得多次Top名次.现 ...

  3. 使用Python解压zip、rar文件

    解压 zip 文件 基本解压操作 import zipfile''' 基本格式:zipfile.ZipFile(filename[,mode[,compression[,allowZip64]]]) ...

  4. python 解压zip 慢_Python解压ZIP、RAR等常用压缩格式的方法

    解压大杀器 首先祭出可以应对多种压缩包格式的python库:patool.如果平时只用基本的解压.打包等操作,也不想详细了解各种压缩格式对应的python库,patool应该是个不错的选择. pato ...

  5. python解压zip文件_python-29 python解压压缩包的几种方法

    这里讨论使用Python解压例如以下五种压缩文件: .gz .tar .tgz .zip .rar 简单介绍 gz: 即gzip.通常仅仅能压缩一个文件.与tar结合起来就能够实现先打包,再压缩. t ...

  6. 如何快速解压/打开zip/rar/7z文件包?在线解压工具推荐

    看了很多帖子,都是推荐下载解压软件进行解压,推荐一个在线版的解压服务. 用浏览器开箱即用.现在已经支持.zip.zipx.rar.tar.gz.tgz.7z.采用的是前端的技术栈,所以解压服务是发生在 ...

  7. python解压zip文件_Python中最快解压zip文件的方法

    假设现在的上下文(LCTT 译注:context,计算机术语,此处意为业务情景)是这样的:一个 zip 文件被上传到一个Web 服务中,然后 Python 需要解压这个 zip 文件然后分析和处理其中 ...

  8. python 解压zip密码正确但解压失败,Python实现加密的ZIP文件解压(密码已知

    当ZIP文件的压缩密码已知时,可以通过调用zipfile库进行解压: import zipfile zip_file = zipfile.ZipFile(r'C:\test.zip') # 文件的路径 ...

  9. python 解压zip文件_Python 解压缩文件详解

    zipfile模块及相关方法介绍: 1 压缩 1.1 创建zipfile对象 zipfile.ZipFile(file, mode='r', compression=0, allowZip64=Tru ...

  10. python h5s文件 压缩_如何用python解压zip压缩文件

    前言:python在办公上非常有用,它可以解压文件,可以处理表格,还可以操作浏览器,只要你能想到的功能,它都能做到,今天笔者就为大家介绍一下如何用处理压缩文件. 打开cmd,输入python3,今天的 ...

最新文章

  1. Python培训讲解二叉树的三种深度
  2. 震精~python运算符还能这么玩~到底这么做到的?神级程序员解密!
  3. Java连接Oracle数据库常用方法
  4. poj 1200 Crazy Search
  5. 一周一论文(翻译)——[PVLDB 17] Dhalion: 基于Heron自适应调整的流处理系统
  6. hiho一下 第三周 Hiocoder #1015 : KMP算法
  7. 提取图片纹理_Fundamentals Of Computer Graphics 第十一章 纹理映射(中)
  8. 中国大学MOOC 计算机组成原理第3章 测试
  9. fiddler插件开发
  10. LeetCode MySQL 180. 连续出现的数字(cast)
  11. iconpath 微信小程序_微信小程序开发(全局配置文件)
  12. JAVA利用google的zxing快速生成QRCode
  13. python点击屏幕_python实现鼠标自动点击屏幕
  14. 怎样取消手机QQ浏览器自动推送新闻广告
  15. 程序员壁纸推荐,高清无码无水印地址已奉上!
  16. 运用HTML制作简单效果
  17. win10系统更新之后经常蓝屏解决方法分享
  18. linux命令 dmesg_如何在Linux上使用dmesg命令
  19. 室内定位之行人航位推算(PDR)
  20. 车载定位与轨迹服务系统

热门文章

  1. 使用AdoptOpenJDK替代Oracle JDK
  2. cisco1841(cisco1841路由器设置步骤)
  3. android11 谷歌安装器,gms安装器安卓11版2021最新版-安卓11gms安装器2021最新版v4.8.5华为专版_新绿资源网...
  4. 想学一门技术,学java有前途吗?
  5. Ensembl数据库简介
  6. devc语言图形编程教程_C语言编程工具:Dev - C++ 简单安装和使用!新手福利!
  7. 数据结构与算法-进阶(十二)最短路径Dijkstra 算法
  8. VO、DO、DTO、PO是什么
  9. 2020德勤面试开始了吗_四大面试-德勤面试流程免费给你,还不收好?截止2020年9月...
  10. 计算机 随机分组的方法,最小化随机分组方法介绍及其SAS实现