pythonurllibhttplib

python httplib/urllib get filename


is there a possibillity to get the filename

e.g. xyz.com/blafoo/showall.html

if you work with urllib or httplib?

so that i can save the file under the filename on the server?

if you go to sites like

xyz.com/blafoo/ 

you cant see the filename.

Thank you


Solution

  • To get filename from response http headers:

    import cgi
    
    response = urllib2.urlopen(URL)
    _, params = cgi.parse_header(response.headers.get('Content-Disposition', ''))
    filename = params['filename']
    

    To get filename from the URL:

    import posixpath
    import urlparse 
    
    path = urlparse.urlsplit(URL).path
    filename = posixpath.basename(path)