小编典典

urllib2文件名

python

如果我使用urllib2打开文件,如下所示:

remotefile = urllib2.urlopen('http://example.com/somefile.zip')

除了解析原始URL之外,是否有一种简单的方法来获取文件名?

编辑:将openfile更改为urlopen …不确定如何发生。

EDIT2:我最终使用:

filename = url.split('/')[-1].split('#')[0].split('?')[0]

除非我没有记错,否则这也应消除所有潜在查询。


阅读 146

收藏
2020-12-20

共1个答案

小编典典

您是说urllib2.urlopen吗?

如果 服务器通过检查发送了Content-Disposition标头, 可能会取消 预期的 文件名,但是我认为您只需要解析url。
__remotefile.info()['Content-Disposition']

您可以使用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'
2020-12-20