python截图直接在内存里调用_Python-使用请求将文件直接下载到内存

The goal is to download a file from the internet, and create from it a file object, or a file like object without ever having it touch the hard drive. This is just for my knowledge, wanting to know if its possible or practical, particularly because I would like to see if I can circumvent having to code a file deletion line.

This is how I would normally download something from the web, and map it to memory:

import requests

import mmap

u = requests.get("http://www.pythonchallenge.com/pc/def/channel.zip")

with open("channel.zip", "wb") as f: # I want to eliminate this, as this writes to disk

f.write(u.content)

with open("channel.zip", "r+b") as f: # and his as well, because it reads from disk

mm = mmap.mmap(f.fileno(), 0)

mm.seek(0)

print mm.readline()

mm.close() # question: if I do not include this, does this become a memory leak?

解决方案

This is what I ended up doing.

import zipfile

import requests

import StringIO

u = requests.get("http://www.pythonchallenge.com/pc/def/channel.zip")

f = StringIO.StringIO()

f.write(u.content)

def extract_zip(input_zip):

input_zip = zipfile.ZipFile(input_zip)

return {i: input_zip.read(i) for i in input_zip.namelist()}

extracted = extract_zip(f)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值