如果我使用 urllib2 打开文件,如下所示:
remotefile = urllib2.urlopen('http://example.com/somefile.zip')
除了解析原始 URL 之外,是否有一种简单的方法来获取文件名?
编辑:将打开的文件更改为 urlopen...不知道这是怎么发生的。
编辑2:我最终使用了:
filename = url.split('/')[-1].split('#')[0].split('?')[0]
除非我弄错了,否则这也应该消除所有潜在的查询。
你的意思urllib2.urlopen http://www.python.org/doc/2.5.2/lib/module-urllib2.html#l2h-3928?
您可能会解除intended文件名if服务器通过检查发送 Content-Disposition 标头remotefile.info()['Content-Disposition']
,但事实上我认为你只需要解析 url 即可。
你可以使用urlparse.urlsplit
,但是如果您有任何像第二个示例中那样的 URL,您最终将不得不自己提取文件名:
>>> urlparse.urlsplit('http://example.com/somefile.zip')
('http', 'example.com', '/somefile.zip', '', '')
>>> urlparse.urlsplit('http://example.com/somedir/somefile.zip')
('http', 'example.com', '/somedir/somefile.zip', '', '')
不妨这样做:
>>> 'http://example.com/somefile.zip'.split('/')[-1]
'somefile.zip'
>>> 'http://example.com/somedir/somefile.zip'.split('/')[-1]
'somefile.zip'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)