Home > Mobile >  How Can I Read Files directly from its url
How Can I Read Files directly from its url

Time:06-11

url = 'https://cdn.wsform.com/wp-content/uploads/2021/05/currency.csv'

f = open(url, 'r')
print(f.read())

Invalid argument: 'https://cdn.wsform.com/wp-content/uploads/2021/05/currency.csv'

Is there any way so that i can read file from url, instead of downloading it ??

CodePudding user response:

Yes, the standard urllib.request.urlopen() does exactly that:

from urllib import request

with request.urlopen('https://cdn.wsform.com/wp-content/uploads/2021/05/currency.csv') as f:
    print(f.read().decode())  # the decode turns the bytes into a string for printing

Just note that the file is opened as a file of bytes, since the function can't know if it's a text file or not.

  • Related