How to parse filename extension from URL using Python

If you have an URL like

example.txt
https://logodix.com/logo/1667872.jpg?param=value

and you want to find just the filename extension (.jpg for this example), use the following code:

example.py
from urllib.parse import urlsplit
import os.path

url = "https://logodix.com/logo/1667872.jpg?param=value"

path = urlsplit(url).path
extension = os.path.splitext(path)[-1] # e.g. ".jpg"

 


Check out similar posts by category: Python