请求:从url返回文件对象(与open('','rb')一样)

时间:2015-05-05 09:36:11

标签: python file download python-requests pypdf

我想使用requests将文件直接下载到内存中,以便将其直接传递给PyPDF2读者,避免将其写入磁盘,但我无法弄清楚如何将其作为传递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)

0 个答案:

没有答案