urllib2.urlopen如何打开本地文件,跨平台

4

我想使用urllib2打开一个本地文件,代码如下:

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

虽然这在Unix上可以工作,但由于//,它在Windows上无法工作。最符合Python风格的跨平台解决方案是什么?


3
如果你使用file:///(三个斜杠)你的代码将可以工作。但是some_path必须使用斜杠形式 c:/path/ - jheyse
2个回答

7
使用urllib.pathname2url函数:
>>> import urllib
>>> 'file:' + urllib.pathname2url(r'c:\path\to\something')
'file:///C:/path/to/something'

0

这个函数在Python 3中的位置已经改变。现在它是urllib.request.pathname2url。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接