我想使用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)