How to extract file name from URL and add word to it?

I have the following URL:

url = http://photographs.500px.com/kyle/09-09-201315-47-571378756077.jpg

I would like to extract the file name in this URL: 09-09-201315-47-571378756077.jpg

As soon as I get this file name, I am going to save it with this name on the desktop.

filename = **extracted file name from the url** download_photo = urllib.urlretrieve(url, "/home/ubuntu/Desktop/%s.jpg" % (filename)) 

After that, I'm going to resize the photo, as soon as this is done, I will save the modified version and add the word "_small" at the end of the file name.

 downloadedphoto = Image.open("/home/ubuntu/Desktop/%s.jpg" % (filename)) resize_downloadedphoto = downloadedphoto.resize.((300, 300), Image.ANTIALIAS) resize_downloadedphoto.save("/home/ubuntu/Desktop/%s.jpg" % (filename + _small)) 

Based on this, I try to get two files: the original photo with the original name, and then the changed photo with the changed name. Like this:

09-09-201315-47-571378756077.jpg

09-09-201315-47-571378756077_small.jpg

How can I do it?

+21
source share
6 answers
 filename = url[url.rfind("/")+1:] filename_small = filename.replace(".", "_small.") 

it is possible to use ".jpg" in the latter case, since a. may also be in the file name.

+14
source

You can use urlparse and os.path python built-in modules. Example:

 >>> import urlparse, os >>> url = "http://photographs.500px.com/kyle/09-09-201315-47-571378756077.jpg" >>> a = urlparse.urlparse(url) >>> a.path '/kyle/09-09-201315-47-571378756077.jpg' >>> os.path.basename(a.path) '09-09-201315-47-571378756077.jpg' 

If you are having problems importing urlparse , try the following:

Python 2

 from six.moves.urllib.parse import urlparse 

Python 3

 from urllib.parse import urlparse 
+73
source

You can simply split the URL into "/" and get the last element of the list:

  url = "http://photographs.500px.com/kyle/09-09-201315-47-571378756077.jpg" filename = url.split("/")[-1] #09-09-201315-47-571378756077.jpg 

Then use replace to change the ending:

  small_jpg = filename.replace(".jpg", "_small.jpg") #09-09-201315-47-571378756077_small.jpg 
+10
source

os.path.basename(url)

Why try hard?

 In [1]: os.path.basename("https://foo.com/bar.html") Out[1]: 'bar.html' In [2]: os.path.basename("https://foo.com/bar") Out[2]: 'bar' In [3]: os.path.basename("https://foo.com/") Out[3]: '' In [4]: os.path.basename("https://foo.com") Out[4]: 'foo.com' 
+8
source

Python split URL to find filename and filename extension

helps you extract the name of the image. add name:

 imageName = '09-09-201315-47-571378756077' new_name = '{0}_small.jpg'.format(imageName) 
+1
source

Sometimes there is a query string:

 filename = url.split("/")[-1].split("?")[0] new_filename = filename.replace(".jpg", "_small.jpg") 
0
source

Source: https://habr.com/ru/post/1501545/


All Articles