简体   繁体   中英

Save the name of an image from a url

I need to find a way to get the image name of any given image from a url. For example, in ".../images/foo.png", the image name is "foo.png". Is there a way to read this url and save just the name of the image up until the "/"? Thanks!

You can just use split :

url = 'https://upload.wikimedia.org/wikipedia/en/d/d0/Dogecoin_Logo.png'
*_, filename = url.split('/')
print(filename)
# Outputs Dogecoin_Logo.png

this is a beginner-friendly way. the split method returns a list of sections from the string so you just take the last one since it's what you want.

url = 'https://upload.wikimedia.org/wikipedia/en/d/d0/Dogecoin_Logo.png'
filename = url.split("/")[-1]
print(filename)

It's not a good idea to use split on its own with arbitrary URLs, because they might have query or path parameters which mean you don't get the correct file name: you only want the last segment of the URL path. Python has a built in URL parser which should help with this .

from urllib.parse import urlparse

url = "https://example.com/some/path/with/image%20name.png?width=640px&height=640px"

parsed_url = urlparse(url)
url_path = parsed_url.path

image_name = url_path.split("/")[-1]
print(image_name)  # 'image%20name.png'

Additionally, though, you probably want to decode any special characters in the file name (like spaces) using unquote :

from urllib.parse import unquote

image_name = unquote(image_name)
print(image_name)  # 'image name.png'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM