urllib2文件名

def*_*rex 31 python url urllib2

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

remotefile = urllib2.urlopen('http://example.com/somefile.zip')
Run Code Online (Sandbox Code Playgroud)

有没有一种简单的方法来获取文件名,然后解析原始URL?

编辑:将openfile更改为urlopen ...不确定是怎么回事.

编辑2:我最终使用:

filename = url.split('/')[-1].split('#')[0].split('?')[0]
Run Code Online (Sandbox Code Playgroud)

除非我弄错了,否则这也应该删除所有潜在的查询.

Jon*_*nan 49

你的意思是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', '', '')
Run Code Online (Sandbox Code Playgroud)

不妨这样做:

>>> 'http://example.com/somefile.zip'.split('/')[-1]
'somefile.zip'
>>> 'http://example.com/somedir/somefile.zip'.split('/')[-1]
'somefile.zip'
Run Code Online (Sandbox Code Playgroud)

  • 我会*总是*使用urlsplit()而不是直接字符串拆分.如果你有一个附加了片段或查询的URL,后者会阻塞,比如http://example.com/filename.html?cookie=55#Section_3. (8认同)
  • 使用posixpath.basename()而不是手动拆分'/'. (7认同)

Jay*_*Jay 13

如果您只想要文件名本身,假设最后没有查询变量,如http://example.com/somedir/somefile.zip?foo=bar,那么您可以使用os.path.basename:

[user@host]$ python
Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) 
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.path.basename("http://example.com/somefile.zip")
'somefile.zip'
>>> os.path.basename("http://example.com/somedir/somefile.zip")
'somefile.zip'
>>> os.path.basename("http://example.com/somedir/somefile.zip?foo=bar")
'somefile.zip?foo=bar'
Run Code Online (Sandbox Code Playgroud)

其他一些海报提到使用urlparse,这将起作用,但你仍然需要从文件名中删除前导目录.如果使用os.path.basename(),那么您不必担心,因为它只返回URL或文件路径的最后部分.

  • 使用`os.path`来解析URL似乎依赖于当前的操作系统拆分路径,就像拆分URL一样.我不认为每个操作系统都能保证. (3认同)

Raf*_*ird 7

我认为"文件名"在http传输方面并不是一个定义明确的概念.服务器可能(但不是必须)提供一个"content-disposition"标头,您可以尝试使用它remotefile.headers['Content-Disposition'].如果失败,您可能必须自己解析URI.


小智 5

刚刚看到我通常做的..

filename = url.split("?")[0].split("/")[-1]
Run Code Online (Sandbox Code Playgroud)