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
相关文章
- pycharm连接mysql数据库代码_怎么把Python与pycharm连接
- Python列表详细操作
- 遗传算法做多目标优化_python 遗传算法
- Linux 上使用 crontab 设置定时任务及运行 Python 代码不执行的解决方案
- Python基础17-面向对象
- 用 Python 破解 WiFi 密码,太刺激了!
- python 字符串(字符序列)和字节序列
- python和c++哪个好_run pycharm community edition
- 恢复pycharm中误删的Python文件
- 分类变量的卡方检验(python实现&SPSS实现)「建议收藏」
- python lambda表达式详解_lambda python
- pycharm提示no python interpreter_pycharm代码运行不了
- 干货 | OpenCV获取不规则区域的最大内切圆(附Python / C++ 源码)
- Python进阶40-drf框架(二)
- 【记录】mac使用PyCharm中Python版本不对应的解决方法
- pycharm调试python_pycharm调试快捷键
- 一对兔子从出生后第三个月起每个月_兔子繁衍问题python
- Python进阶41-drf框架(三)
- Python-drf前戏38-前端Vue
- Python基础10-函数的递归