if 'Content-Disposition' in r.info():
    localName = r.info()['Content-Disposition'].split('filename=')[1]
if localName[0] == '"' or localName[0] == "'":
    localName = localName[1:-1]
elif r.url != url:
    localName = url2name(r.url)
if localFileName:
    localName = localFileName
f = open(localName, 'wb')
f.write(r.read())
f.close()
How to download a file using python in a 'smarter' way?