使用Python3解压gz、tar、tgz、zip、rar五种格式的压缩文件例子

使用Python3解压如下五种压缩文件:gz、tar、tgz、zip、rar

简介

gz: 即gzip,通常只能压缩一个文件。与tar结合起来就可以实现先打包,再压缩。

tar: linux系统下的打包工具,只打包,不压缩

tgz:即tar.gz。先用tar打包,然后再用gz压缩得到的文件

zip: 不同于gzip,虽然使用相似的算法,可以打包压缩多个文件,不过分别压缩文件,压缩率低于tar。

rar:打包压缩文件,最初用于DOS,基于window操作系统。压缩率比zip高,但速度慢,随机访问的速度也慢。

例子

import gzip
import os
import tarfile , zipfile, rarfile

from library.utils.file import get_filetype
from library.utils.path import make_dir
from library.utils.type_conv import random_str

def uncompress(src_file, dest_dir):
    result = get_filetype(src_file)
    if not result[0] :
        return (False, result[1], '')
    filefmt = result[1]

    result = make_dir(dest_dir)
    if not result :
        return (False, '创建解压目录失败', filefmt)

    if filefmt in ('tgz', 'tar') :
        try :
            tar = tarfile.open(src_file)  
            names = tar.getnames()   
            for name in names:  
                tar.extract(name, dest_dir)  
            tar.close()
        except Exception as e :
            return (False, e, filefmt)
    elif filefmt == 'zip':
        try :
            zip_file = zipfile.ZipFile(src_file)  
            for names in zip_file.namelist():  
                zip_file.extract(names, dest_dir)  
            zip_file.close()  
        except Exception as e :
            return (False, e, filefmt)
    elif filefmt == 'rar' :
        try :
            rar = rarfile.RarFile(src_file)  
            os.chdir(dest_dir)
            rar.extractall()  
            rar.close()  
        except Exception as e :
            return (False, e, filefmt)
    elif filefmt == 'gz' :
        try :

            f_name = dest_dir + '/' + os.path.basename(src_file)
            # 获取文件的名称,去掉  
            g_file = gzip.GzipFile(src_file)  
            # 创建gzip对象  
            open(f_name, "w+").write(g_file.read())  
            # gzip对象用read()打开后,写入open()建立的文件中。  
            g_file.close()  
            # 关闭gzip对象  

            result = get_filetype(src_file)
            if not result[0] :
                new_filefmt = '未知'
            else :
                new_filefmt = result[1]
            return (True, '解压后的文件格式为:' + new_filefmt, filefmt)
        except Exception as e :
            return (False, e, filefmt)
    else :
        return (False, '文件格式不支持或者不是压缩文件', filefmt)

    return (True, '', filefmt)

转载于:https://www.cnblogs.com/lykops/p/8263112.html

Python中批量解压ziprartargz压缩文件时,文件名称出现乱码通常是由于编码问题导致的。为了避免这种情况,可以采取以下几种方法: 1. **使用正确的编码方式**: 确保在解压使用正确的编码方式。例如,zip文件默认使用UTF-8编码,但有些文件可能使用GBK编码。 2. **处理异常**: 在解压过程中捕获异常,并尝试使用不同的编码方式进行解码。 3. **使用第三方库**: 使用更强大的库如`rarfile`来处理rar文件,并确保安装相应的支持工具。 以下是一个示例代码,展示了如何批量解压不同类型的压缩文件,并处理文件名称乱码问题: ```python import os import zipfile import tarfile import rarfile def unzip_file(zip_path, extract_to): try: with zipfile.ZipFile(zip_path, 'r') as zip_ref: for file in zip_ref.namelist(): try: zip_ref.extract(file, extract_to) except UnicodeEncodeError: # 尝试使用GBK编码 file_encoded = file.encode('cp437').decode('gbk') zip_ref.extract(file_encoded, extract_to) except Exception as e: print(f"Error unzipping {zip_path}: {e}") def untar_file(tar_path, extract_to): try: with tarfile.open(tar_path, 'r') as tar_ref: tar_ref.extractall(extract_to) except Exception as e: print(f"Error untarring {tar_path}: {e}") def unrar_file(rar_path, extract_to): try: with rarfile.RarFile(rar_path) as rar_ref: rar_ref.extractall(extract_to) except Exception as e: print(f"Error unrar-ing {rar_path}: {e}") def process_file(file_path, extract_to): if file_path.endswith(('.zip', '.ZIP')): unzip_file(file_path, extract_to) elif file_path.endswith(('.tar', '.gz', '.tgz', '.TAR', '.GZ', '.TGZ')): untar_file(file_path, extract_to) elif file_path.endswith(('.rar', '.RAR')): unrar_file(file_path, extract_to) def batch_extract(files_path, extract_to): for file in os.listdir(files_path): full_path = os.path.join(files_path, file) if os.path.isfile(full_path): process_file(full_path, extract_to) # 示例使用 files_path = 'path_to_your_zip_files' extract_to = 'path_to_extract_files' batch_extract(files_path, extract_to) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值