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]

print(pieces)
print(filename)

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

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

Please help.

Post a Reply

Replies

Oldest  Newest  Rating
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.

Thanks.
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 10, 2014
thanks
the os.path.basename worked for me.
+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)
print(filename)
+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, 
print(filename[0])

you could also try:

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

print(pieces)
print(pieces[-1])
  • 1

Python

107,085 followers
About

This section is all about snakes! Just kidding.

Links
Moderators
Bucky Roberts Administrator