0

I'm quite new with Python, and I'm trying to find out how to read a remote file without having to download it. Normally, if the file is on my HDD, I just have to do

with open('file.jpg', "rb") as file:
   data = file.read()

And then I have a stream of my file.

Now, if the file is located at a http://.../file.jpg I obviously can't use open(). I don't want to download it then open it from hard drive but directly stream it from its original URL. How can I do that? Thank you in advance.

3
  • 4
    Use the requests module to read from URLs. Commented Aug 22, 2022 at 22:27
  • 1
    I would like to add that it would be courteous to save the file to the user's disk too once you've got it for the first time, to save their bandwidth and the host's Commented Aug 22, 2022 at 22:31
  • 1
    Although you could use a third party library like requests, Python's own urllib.request.urlopen works in most simple cases and functions just like open() for files, which is convenient. Commented Aug 22, 2022 at 22:34

1 Answer 1

2
import requests
from io import BytesIO
from PIL import Image

img = Image.open(BytesIO(requests.get(url).content))
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.