Extract file name from path, no matter what the os/path format

There’s a function that returns exactly what you want

import os

WARNING: When os.path.basename() is used on a POSIX system to get the base name from a Windows-styled path (e.g. "C:\\my\\file.txt"), the entire path will be returned.

Example below from interactive python shell running on a Linux host:

Python 3.8.2 (default, Mar 13 2020, 10:14:16)
[GCC 9.3.0] on Linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> filepath = "C:\\my\\path\\to\\file.txt" # A Windows style file path.
>>> os.path.basename(filepath)

Leave a Comment