Python对zip、tgz、rar压缩包的解压与读取

先安装相关的包:

import os
import tarfile
import unrar           # 直接pip install unrar
from unrar import rarfile      
import zipfile

注意:安装完unrar后,from unrar import rarfile可能会报错:Couldn’t find path to unrar library.

windows和Linux的解决方法可以参考博客:
https://blog.csdn.net/ysy950803/article/details/52939708

tgz:

def un_tgz(filename):      # filename是文件的绝对路径
       tar=tarfile.open(filename)
       #判断是否存在同名文件夹,若不存在则创建同名文件夹:
       if os.path.isdir(os.path.splitext(filename)[0]):
           pass
       else:
           os.mkdir(os.path.splitext(filename)[0])
       tar.extractall(os.path.splitext(filename)[0])
       tar.close()

rar:

def un_rar(filename):    # filename是文件的绝对路径
    rar=rarfile.RarFile(filename)
    #判断是否存在同名文件夹,若不存在则创建同名文件夹:
    if os.path.isdir(os.path.splitext(filename)[0]):
        pass
    else:
        os.mkdir(os.path.splitext(filename)[0])
    rar.extractall(os.path.splitext(filename)[0])

zip:

def un_zip(filename):   # filename是文件的绝对路径
       zip_file=zipfile.ZipFile(filename)
       #判断同名文件夹是否存在,若不存在则创建同名文件夹
       if os.path.isdir(os.path.splitext(filename)[0]):
           pass
       else:
           os.mkdir(os.path.splitext(filename)[0])
       for names in zip_file.namelist():
           zip_file.extract(names,os.path.splitext(filename)[0])
       zip_file.close()

上面三个代码运行后,会产生一个和压缩文件同名的的文件夹,解压后的文件就在这个同名文件夹里面:。再读取就好了

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值