gpt4 book ai didi

python - urllib2 文件名

转载 作者:IT老高 更新时间:2023-10-28 21:59:07 27 4
gpt4 key购买 nike

如果我使用 urllib2 打开一个文件,像这样:

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

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

编辑:将 openfile 更改为 urlopen...不确定这是怎么发生的。

EDIT2:我最终使用了:

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

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

最佳答案

你是说urllib2.urlopen ?

您可能会通过检查 remotefile.info()['Content-Disposition' 来提升 intended 文件名 if 服务器正在发送 Content-Disposition header ],但我认为你只需要解析 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'

关于python - urllib2 文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/163009/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com