Tôi muốn tải xuống tệp thẳng vào bộ nhớ bằng cách sử dụng requests
để chuyển trực tiếp tới trình đọc PyPDF2
để tránh ghi vào đĩa, nhưng Tôi không thể tìm ra cách để vượt qua nó như là một file object
. Đây là những gì tôi đã cố gắng:YÊU CẦU: Trả về đối tượng tệp từ url (giống như mở ('', 'rb'))
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)
Hoạt động tuyệt vời. Cảm ơn. – TimY
Bumping câu trả lời tốt đẹp, súc tích này. Tôi tự hỏi, @abarnert, là có một nguồn tài nguyên có thể phác thảo những phương pháp đối tượng tập tin giống như không có sẵn trong các đối tượng StringIO? – ghukill