How do I get the name with the file extension in a Python URL?

Asked

Viewed 320 times

0

I want to extract the name of an image with its given extension uses full URL, for example:

image_url = 'http://dominio.com.br/caminho/da/imagem/imagem.png'

I want to have only:

image = 'imagem.png'

There is a ready-made Python function to simplify this?

1 answer

3


Just take the value of path of the URL and divide it into the bar character:

from urllib.parse import urlsplit

url = 'http://dominio.com.br/caminho/da/imagem/imagem.png'

parts = urlsplit(url)
paths = parts.path.split('/')

print(paths[-1])  # imagem.png
  • In that case because I would need to import the module urlsplit? The function split alone is not a conventional method for doing this?

  • 2

    @Whoismatt are not euivalentes. There are other parts that could exist in the URL that function split does not consider. For example, in the URL http://localhost/imagem.png?cache=false#foo by just doing the split you would have imagem.png?cache=false#foo. With the urlsplit we were able to separate each part of the URL and analyze only the path of the same, ignoring the query strings and Fragment.

  • Got it, thanks for the tip. I will now use this module then :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.