Extract file name from URL

+1 Moiz Nagpur · December 7, 2014
Hello all,

I am trying to extract file name of an image from URL.

Here is what I tried:

url = "http://www.somedomain.com/uploads/some-image-name.jpg"
pieces = url.split("/")
length = len(pieces)
filename = pieces[length - 1:length]


it prints:
['http:', '', 'www.somedomain.com', 'uploads', 'some-image-name.jpg']

How to get rid of those [' '] around the output?

Please help.

Post a Reply


Oldest  Newest  Rating
+2 Vaggelis Theodoridis · December 8, 2014
You can do it also with os.path.basename
import os
url = "http://www.somedomain.com/uploads/some-image-name.jpg"
filename = os.path.basename(url)
+1 Doug Fresh · December 7, 2014
to print the string in a list, you will need to reference the position of the list, in this case, 

you could also try:

url = "http://www.somedomain.com/uploads/some-image-name.jpg"
pieces = url.split("/")

0 Moiz Nagpur · December 10, 2014
the os.path.basename worked for me.
0 Vaggelis Theodoridis · December 10, 2014
well both work
Your way to find the last element of ur list isnt wrong. But theres a more "pythonic" way.
You can select positions in lists in reverse way like Doug Fresh posted.
Reverse way means that starts from the end of the list.

list = [0, 1, "abc"]

lista[-1] -> "abc"

lista[-2] -> 1

The -1 -2 -3 etc are Positions not elements, elements are 0,1,"abc"
So in a list we can find positions the usual way a[0] a[1] or the reverse way a[-1] etc

Now if you want to delete an element from a list (even if i dont see the point in your example), in your question the second element, you can do:
pieces.remove('')  # deletes the FIRST Element that matches in list, if element doesnt exist in list ValueError is raised, so if you had 2 empty strings like '', the first '' would be deleted.

pieces.pop(1)  # deletes the Position 1 and returns it's element

pieces.del(1)  # deletes position 1 (and it's element of course)

Anyway you dont have to use mine solution, importing os etc. As u did it, split the list and then just select the last element list[-1] 
0 Moiz Nagpur · December 11, 2014
Thanks Vaggelis for the explanation there.

I'm coming from VB.NET world, so your os.path approach sounded more familiar to me.

By the way, I used os.path which lead me to read the documentation. Which was very informative.

  • 1



This section is all about snakes! Just kidding.

Bucky Roberts Administrator