urllib2 file name

前端 未结 14 1833
感动是毒
感动是毒 2020-12-01 03:27

If I open a file using urllib2, like so:

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

Is there an easy way to get the

14条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-01 04:22

    Did you mean urllib2.urlopen?

    You could potentially lift the intended filename if the server was sending a Content-Disposition header by checking remotefile.info()['Content-Disposition'], but as it is I think you'll just have to parse the url.

    You could use urlparse.urlsplit, but if you have any URLs like at the second example, you'll end up having to pull the file name out yourself anyway:

    >>> 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', '', '')
    

    Might as well just do this:

    >>> 'http://example.com/somefile.zip'.split('/')[-1]
    'somefile.zip'
    >>> 'http://example.com/somedir/somefile.zip'.split('/')[-1]
    'somefile.zip'
    

提交回复
热议问题