目标是从互联网上下载文件,并从中创建一个文件对象,或者像对象这样的文件,而不必触摸硬盘.这只是为了我的知识,想要知道它是否可行或实用,特别是因为我想看看我是否可以避免编写文件删除行.
这就是我通常从网上下载内容并将其映射到内存的方式:
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?
Run Code Online (Sandbox Code Playgroud)