urllib2 file name

前端 未结 14 1825
感动是毒
感动是毒 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:17

    The os.path.basename function works not only for file paths, but also for urls, so you don't have to manually parse the URL yourself. Also, it's important to note that you should use result.url instead of the original url in order to follow redirect responses:

    import os
    import urllib2
    result = urllib2.urlopen(url)
    real_url = urllib2.urlparse.urlparse(result.url)
    filename = os.path.basename(real_url.path)
    

提交回复
热议问题