请求:来自 url 的 Return 文件对象(与 open('','rb') 一样)

REQUESTS: Return file object from url (as with open('','rb') )

我想使用 requests 将文件直接下载到内存中,以便将其直接传递给 PyPDF2 reader 避免将其写入磁盘,但我无法弄清楚如何将其作为 file object 传递。这是我尝试过的:

import requests as req
from PyPDF2 import PdfFileReader

r_file = req.get('http://www.location.come/somefile.pdf')
rs_file = req.get('http://www.location.come/somefile.pdf', stream=True)

with open('/location/somefile.pdf', 'wb') as f:
    for chunk in r_file.iter_content():
        f.write(chunk)

local_file = open('/location/somefile.pdf', 'rb')

#Works:
pdf = PdfFileReader(local_file)

#As expected, these don't work:
pdf = PdfFileReader(rs_file)
pdf = PdfFileReader(r_file)
pdf = PdfFileReader(rs_file.content)
pdf = PdfFileReader(r_file.content)
pdf = PdfFileReader(rs_file.raw)
pdf = PdfFileReader(r_file.raw)

无需了解任何有关 requests 的信息,您始终可以使用 StringIO.

将内存中的任何内容作为字符串创建一个类似文件的对象

特别是:

  • Python 2 StringIO.StringIO(s)是一个二进制文件。
  • Python 2 cStringIO.StringIO(s) 是一样的,但可能更有效率。
  • Python 3 io.BytesIO(b)是一个二进制文件(由bytes构建)。
  • Python 3 io.StringIO(s) 是一个 Unicode 文本文件。
  • Python 2 io.BytesIO(s)是一个二进制文件。
  • Python 2 io.StringIO(u) 是一个 Unicode 文本文件(由 unicode 构建)。

(前两个是 Python 2 意义上的 "binary"——没有行尾转换。其他是 "binary" 与 "text" Python 3 sense--bytes vs. Unicode。)

因此,io.BytesIO(response.content) 在 Python 2 和 Python 3 中都为您提供了一个有效的类似二进制文件的对象。如果您只关心 Python 2,cStringIO.StringIO(response.content) 可能更有效率。

当然 "file-like" 到此为止;例如,如果库试图调用 fileno 方法并开始对文件描述符进行 C 调用,它将无法工作。但在 99% 的情况下,这是有效的。