Search code examples
pythoncross-platformurllib2

urllib2.urlopen a local file, cross platform


I'm trying to open a local file using urllib2 and have the following code:

r = urllib2.urlopen('file://' + some_path)

While this works on Unix, it does not work on Windows because of the //. What is the most pythonic way to have this work cross-platform?


Solution

  • Use urllib.pathname2url:

    >>> import urllib
    >>> 'file:' + urllib.pathname2url(r'c:\path\to\something')
    'file:///C:/path/to/something'