Python: how to extract the file name from a URL

In this article we will see how to extract the file name from a URL in Python.

We basically need to get the path value from the URL and with this value extract the filename using a specific method of the os core module.

import os
from urllib.parse import urlsplit

def get_filename_from_url(url=None):
    if url is None:
        return None
    urlpath = urlsplit(url).path
    return os.path.basename(urlpath)

Wanting to make our function even more robust, we could add a validation using regular expressions that checks if the URL actually contains a reference to a file.

Back to top