urllib2 file name

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("https://stackoverflow.com/")[-1]
'somefile.zip'
>>> 'http://example.com/somedir/somefile.zip'.split("https://stackoverflow.com/")[-1]
'somefile.zip'

Leave a Comment