Python程序教程

您现在的位置是:首页 >  Python

当前栏目

python 快速读取压缩包内文件

python,快速,读取,压缩包,文件
2025-03-13 21:27:17 时间

python 快速读取压缩包内文件

作者:matrix 被围观: 5,421 次 发布时间:2019-10-14 分类:Python | 无评论 »

这是一个创建于 1052 天前的主题,其中的信息可能已经有所发展或是发生改变。

搜索结果一大堆但都没有找到支持url和local path两种读取方式的操作。 留着便于以后直接使用。

gits: https://gist.github.com/Hootrix/cf3e75b1fa6d3d404bc99787f89687f1

import requests,tempfile, zipfile,os
def read_file_for_zip(zip_url, callback=None):
    """
    读取zip包内的文件
    :param zip_url:zip路径/url
    :param callback:读取操作的回调函数 若函数返回false 则不会读取下一个文件
    :return:
    """
    with tempfile.TemporaryFile('w+b') as tmpfile:  # 生成临时文件

        # 判断是否为本地文件
        if os.path.isfile(zip_url):
            #进行本地复制。没必要
            # with open(zip_url,'rb') as f:
            #     while True:
            #         chunk = f.read(1024)
            #         if not chunk:
            #             break
            #         tmpfile.write(chunk)
            tmpfile = zip_url
        else:#进行http请求
            r = requests.get(zip_url, stream=True)
            for chunk in r.iter_content(chunk_size=1024):
                if chunk:
                    tmpfile.write(chunk)
        assert zipfile.is_zipfile(tmpfile), '不是zip文件'
        zf = zipfile.ZipFile(tmpfile)
        for name in zf.namelist():  # list e.g. ['Brave Browser.url', 'Express VPN.url', 'ssl.txt', 'What is my IP.url']
            if callable(callback):
                # zf.read(name) #读取
                if callback(name, zf) is False:# 函数返回false 会终止下一个文件的读取
                    break


### 例子

def cb(filename,context):
    if filename.endswith('.txt'):
        print(context.read(filename).decode('utf-8'))
    # print( context.read(filename))
        return False #终止下一个文件的读取

read_file_for_zip('https://cdn-01.openload.cc/S9Y7m488n8/22c3c58b-1571037628/ssl_proxies.zip',cb)

具体使用见上面例子 兼容大文件url的下载处理

p.s. 在线压缩包读取: https://extract.me/cn/

参考:

http://www.liujiangblog.com/course/Python/62

https://docs.python.org/2/library/tempfile.html