python 快速读取压缩包内文件

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

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

搜索结果一大堆但都没有找到支持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

其他文章:
本文固定链接:https://www.hhtjim.com/python-fast-read-file-for-zip-archive-extractor.html
matrix
本文章由 matrix 于2019年10月14日发布在Python分类下,目前没有通告,你可以至底部留下评论。
转载请注明:python 快速读取压缩包内文件-HHTjim'S 部落格
关键字:,

添加新评论 »

 🙈 😱 😂 😛 😭 😳 😀 😆 👿 😉 😯 😮 😕 😎 😐 😥 😡 😈 💡

插入图片

NOTICE: You should type some Chinese word (like “你好”) in your comment to pass the spam-check, thanks for your patience!