zip、unrar递归解压缩文件以及zip压缩中文乱码和unrar安装问题的解决

比较简单,就闲话就不说了,直接上代码:

import os
import zipfile
import shutil
from unrar import rarfile



def get_filename(dirname):
    result = []
    for maindir, subdir, filenames in os.walk(dirname):
        for filename in filenames:
            abspath = os.path.join(maindir, filename)
            result.append(abspath)
    return result


def un_zip(filepath):
    temp_dir = os.path.split(filepath)[0]  # 获取压缩文件所在的目录
    if not os.path.exists(temp_dir):
        os.mkdir(temp_dir)
    os.chdir(temp_dir) # 解压到当前文件目录下
    zip_file = zipfile.ZipFile(filepath)
    for file in zip_file.namelist():
    	try:
	        filename = file.encode('cp437').decode('gbk')  # 解决中文乱码的问题
	    except UnicodeDecodeError:
            filename = file.encode('utf-8').decode('utf-8')
        zip_file.extract(file)  # 解压到当前文件
        if os.path.exists(filename): # 如果当前目录下有同名文件夹那么使用当前文件替换 
            shutil.rmtree(filename)
        os.rename(file, filename)  # 重命名为正常的文件名
    zip_file.close()  # 关闭压缩文件的读取器
    os.remove(filepath)  # 删除压缩文件 递归时必须删除,否则无法跳出递归
    for filename in get_filename(temp_dir):
        if os.path.isfile(filename):  # 这句代码必须有,否则会报没有找到filepath的文件路径,原因是递归时将压缩文件删除了,后面函数回归时便找不到了
            if filename.lower().endswith('zip'):
                un_zip(filename)
            if filename.lower().endswith('rar'):
                un_rar(filename)
    return temp_dir

def un_rar(filepath):
    temp_dir = os.path.split(filepath)[0]
    if not os.path.exists(temp_dir):
        os.mkdir(temp_dir)
    rar_file = rarfile.RarFile(filepath)
    rar_file.extractall()
    os.remove(filepath)
    for filename in get_filename(temp_dir):
        if os.path.isfile(filename):
            if filename.lower().endswith('zip'):
                un_zip(filename)
            if filename.lower().endswith('rar'):
                un_rar(filename)
    return temp_dir

unrar运行时可能会抛出Couldn‘t find path to unrar library的错误的,
就需要去下载这个unrar library,事实上它就是UnRAR.dll这个东西。
Windows:
第一步:
下载网址:http://www.rarlab.com/rar/UnRARDLL.exe ,在lunix下应该需要自己编译。
第二步:
安装完后我电脑中的路径为C:\Program Files (x86)\UnrarDLL,win7-32位的朋友可以将它添加到环境变量中,64位的将其中的X64文件夹设置为环境变量,因为unrar模块识别的文件是unrar.dll和unrar.lib,所以将文件夹中的UnRAR.dll和UnRAR.lib用小写重命名。

Linux:
下载地址:http://www.rarlab.com/rar/unrarsrc-5.4.5.tar.gz
下载完后解压:

tar zxvf unrarsrc-5.4.5.tar.gz
cd unrar

然后执行命令:

make lib  //编译库文件
sudo make install-lib  //生成libunrar.so 文件

配置环境变量:

sudo vim /etc/profile

在最后添加加上:

export UNRAR_LIB_PATH=/usr/lib/libunrar.so

使变量生效

source /etc/profile

如果不成功,那么则在~目录下的.bash_profile中配置环境变量,如上面所示一致。

参考:https://blog.csdn.net/u010856284/article/details/77453408?utm_source=blogxgwz7
参考:http://www.bubuko.com/infodetail-2546545.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值