code_junkie

urllib2 file name

Nov 11th, 2011
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. remotefile = urllib2.urlopen('http://example.com/somefile.zip')
  2.  
  3. filename = url.split('/')[-1].split('#')[0].split('?')[0]
  4.  
  5. >>> urlparse.urlsplit('http://example.com/somefile.zip')
  6. ('http', 'example.com', '/somefile.zip', '', '')
  7. >>> urlparse.urlsplit('http://example.com/somedir/somefile.zip')
  8. ('http', 'example.com', '/somedir/somefile.zip', '', '')
  9.  
  10. >>> 'http://example.com/somefile.zip'.split('/')[-1]
  11. 'somefile.zip'
  12. >>> 'http://example.com/somedir/somefile.zip'.split('/')[-1]
  13. 'somefile.zip'
  14.  
  15. >>> from urllib2 import urlparse
  16. >>> print urlparse.urlsplit('http://example.com/somefile.zip')
  17. ('http', 'example.com', '/somefile.zip', '', '')
  18.  
  19. In [9]: urlparse.urlparse('http://example.com/somefile.zip')
  20. Out[9]: ('http', 'example.com', '/somefile.zip', '', '', '')
  21.  
  22. [user@host]$ python
  23. Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04)
  24. Type "help", "copyright", "credits" or "license" for more information.
  25. >>> import os
  26. >>> os.path.basename("http://example.com/somefile.zip")
  27. 'somefile.zip'
  28. >>> os.path.basename("http://example.com/somedir/somefile.zip")
  29. 'somefile.zip'
  30. >>> os.path.basename("http://example.com/somedir/somefile.zip?foo=bar")
  31. 'somefile.zip?foo=bar'
  32.  
  33. url = 'http://example.com/somefile.zip'
Add Comment
Please, Sign In to add comment