urlopen in python3

O

Olive

In python2, I use this code:

a=urllib.urlopen(something)

In python2, this work if "something" is a regular file on the system as
well as a remote URL. The 2to3 script convert this
to urllib.request.urlopen. But it does not work anymore if "something"
is just a file name.

My aim is to let the user specify a "file" on the command line and have
something that works, whatever the "file " actually is: a regular file,
an http url, etc...

Olive
 
N

Nick Cash

In python2, this work if "something" is a regular file on the system as
well as a remote URL. The 2to3 script convert this to
urllib.request.urlopen. But it does not work anymore if "something"
is just a file name.

My aim is to let the user specify a "file" on the command line and have
something that works, whatever the "file " actually is: a regular file,
an http url, etc...

A file path, such as "/etc/passwd", isn't properly a URL, so urllib correctly refuses to handle it. You can make it a URL by using the file:// protocol, i.e. "file:///etc/passwd"... which appears to work in both python2 and python3.
 
O

Olive

Nick Cash said:
A file path, such as "/etc/passwd", isn't properly a URL, so urllib
correctly refuses to handle it. You can make it a URL by using the
file:// protocol, i.e. "file:///etc/passwd"... which appears to work
in both python2 and python3.


That's true a file path is not an URL, yet the python2 behaviour was
handy. I do not know in advance if it is a file or an URL, so
what's the best way to hadle the case? I imagine someling like:

if os.path.exists(something):
something="file://"+os.path.abspath(something)
a=urllib.request.urlopen(something)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top