how to print this text file data using only file:// protocoal

30 Views Asked by At
import urllib.request
data=urllib.request.urlopen("file:///D:/Learnign/pro/Code%20Editor/d.txt")
print(data)

Output:

<addinfourl at 1642793087856 whose fp = <_io.BufferedReader name='D:\\Learnign\\pro\\Code Editor\\d.txt'>>

How to solve this problem? How to print text file data?

1

There are 1 best solutions below

0
Daweo On

urllib.request.urlopen is designed so it could be used as context manager (see with keyword) so I would use something like

import urllib.request
with urllib.request.urlopen("file:///D:/Learnign/pro/Code%20Editor/d.txt") as f:
    print(data.read())

Note that it will probably return bytes, so you might need to decode it providing encoding used with given file, for example if it was UTF-8-encoded then print line might look as follows

print(f.read().decode('utf-8'))

Consult codecs docs for list of supporting encodings.