Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opening Local File Works with urllib but not with urllib2

I'm trying to open a local file using urllib2. How can I go about doing this? When I try the following line with urllib:

resp = urllib.urlopen(url) 

it works correctly, but when I switch it to:

resp = urllib2.urlopen(url) 

I get:

ValueError: unknown url type: /path/to/file 

where that file definitely does exit.

Thanks!

like image 465
Jason Brooks Avatar asked Dec 13 '13 03:12

Jason Brooks


People also ask

What is the difference between Urllib and urllib2?

1) urllib2 can accept a Request object to set the headers for a URL request, urllib accepts only a URL. 2) urllib provides the urlencode method which is used for the generation of GET query strings, urllib2 doesn't have such a function. This is one of the reasons why urllib is often used along with urllib2.

Is urllib2 deprecated?

urllib2 is deprecated in python 3. x. use urllib instaed.

What does Urllib request Urlretrieve do?

In line 14, the urllib. request. urlretrieve() function is used to retrieve the image from the given url and store it to the required file directory.

Does urllib2 work in Python 3?

NOTE: urllib2 is no longer available in Python 3 You can get more idea about urllib.


2 Answers

Just put "file://" in front of the path

>>> import urllib2 >>> urllib2.urlopen("file:///etc/debian_version").read() 'wheezy/sid\n' 
like image 67
John La Rooy Avatar answered Sep 19 '22 03:09

John La Rooy


In urllib.urlopen method: If the URL parameter does not have a scheme identifier, it will opens a local file. but the urllib2 doesn't behave like this.

So, the urllib2 method can't process it.

It's always be good to include the 'file://' schema identifier in both of the method call for the url parameter.

like image 20
Wubao Li Avatar answered Sep 20 '22 03:09

Wubao Li