There's a function that returns exactly what you want

import os
print(os.path.basename(your_path))

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)
'C:\\my\\path\\to\\file.txt'
Answer from stranac on Stack Overflow
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ os.path.html
os.path โ€” Common pathname manipulations
Since different operating systems have different path name conventions, there are several versions of this module in the standard library. The os.path module is always the path module suitable for the operating system Python is running on, and therefore usable for local paths.
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ pathlib.html
pathlib โ€” Object-oriented filesystem paths
Return a new path with the stem changed. If the original path doesnโ€™t have a name, ValueError is raised:
Top answer
1 of 16
1984

There's a function that returns exactly what you want

import os
print(os.path.basename(your_path))

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)
'C:\\my\\path\\to\\file.txt'
2 of 16
1070

Using os.path.split or os.path.basename as others suggest won't work in all cases: if you're running the script on Linux and attempt to process a classic windows-style path, it will fail.

Windows paths can use either backslash or forward slash as path separator. Therefore, the ntpath module (which is equivalent to os.path when running on windows) will work for all(1) paths on all platforms.

import ntpath
ntpath.basename("a/b/c")

Of course, if the file ends with a slash, the basename will be empty, so make your own function to deal with it:

def path_leaf(path):
    head, tail = ntpath.split(path)
    return tail or ntpath.basename(head)

Verification:

>>> paths = ['a/b/c/', 'a/b/c', '\\a\\b\\c', '\\a\\b\\c\\', 'a\\b\\c', 
...     'a/b/../../a/b/c/', 'a/b/../../a/b/c']
>>> [path_leaf(path) for path in paths]
['c', 'c', 'c', 'c', 'c', 'c', 'c']


(1) There's one caveat: Linux filenames may contain backslashes. So on linux, r'a/b\c' always refers to the file b\c in the a folder, while on Windows, it always refers to the c file in the b subfolder of the a folder. So when both forward and backward slashes are used in a path, you need to know the associated platform to be able to interpret it correctly. In practice it's usually safe to assume it's a windows path since backslashes are seldom used in Linux filenames, but keep this in mind when you code so you don't create accidental security holes.

๐ŸŒ
Medium
medium.com โ€บ @johnusa4567 โ€บ python-get-filename-from-path-simple-methods-explained-a5ea7623b38c
Python Get Filename from Path: Simple Methods Explained | by John Usa | Medium
October 4, 2025 - With Path(path).name, you can extract the filename from a given path. For example, Path("/user/data/file.txt").name will return file.txt. Many developers prefer pathlib for its cleaner syntax and readability.
๐ŸŒ
eSparkBiz
esparkinfo.com โ€บ path from any os/path format
How to Extract File Name from Path in Python Easily?
July 30, 2025 - In Python, you can extract just the filename from a full path using either os.path.basename() or pathlib.Path().name.
๐ŸŒ
b.telligent
btelligent.com โ€บ en โ€บ blog โ€บ best-practice-working-with-paths-in-python-part-1-2
Best Practice: Working With Paths In Python (Part 1)
August 25, 2026 - The simple command os.listdir lists all strings, i.e., only the path filenames. Here and in all other examples, I use type hinting for additional code documentation. This syntax became available from Python 3.5 onwards.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how to get just the file name from a file path.
r/learnpython on Reddit: How to get just the file name from a file path.
November 11, 2021 -

I am just wondering how I would be able to save just the file name from a file path. Right now I have the program opening the file explorer and saving the file path to a variable. I am just wondering how I could trim this to save just the name of the file to another variable. Current code:

filepath = askopenfilename(
  filetypes=[("SH File", "*.sh"), ("All Files", "*.*")]
    )
if not filepath:
    return
Find elsewhere
๐ŸŒ
Medium
medium.com โ€บ pythons-gurus โ€บ how-to-use-path-file-and-path-name-in-python-for-file-management-ffe5f382df2f
How to Use Path(__file__) and Path(__name__) in Python for File Management | by Mehedi Khan | Pythonโ€™s Gurus | Medium
February 15, 2025 - When a Python file is run directly, __name__ is set to '__main__'. When the file is imported as a module, __name__ is set to the module's name. __file__ is a special attribute that contains the path to the current module file.
๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python
Get the Filename, Directory, Extension from a Path String in Python | note.nkmk.me
May 8, 2023 - In Python, you can get the filename (basename), directory (folder) name, and extension from a path string or join the strings to generate the path string with the os.path module in the standard library.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-os-path-basename-method
Python | os.path.basename() method - GeeksforGeeks
February 23, 2026 - os.path.basename() method in Python is used to extract the final part of a file path. This final part can be a file name or the last folder name.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ pathlib-module-in-python
Pathlib Module in Python - GeeksforGeeks
Pathlib module makes it easy to inspect various properties of a file or directory path, such as whether it's absolute, its name, extension, parent directory, etc all using simple methods.
Published: June 15, 2026
๐ŸŒ
Python Guides
pythonguides.com โ€บ python-get-filename-from-the-path
Get Filename From Path in Python (pathlib and os.path)
September 16, 2025 - Get the filename from a path in Python with Path.name or os.path.basename, drop the extension with stem, and handle trailing slashes and URLs.
๐ŸŒ
Real Python
realpython.com โ€บ python-pathlib
Python's pathlib Module: Taming the File System โ€“ Real Python
2 days ago - The __file__ attribute contains the path to the file that Python is currently importing or executing. You can pass in __file__ to Path when you need to work with the path to the module itself. For example, maybe you want to get the parent directory with .parent. You may have already noticed that although you enter paths on Windows with backslashes, pathlib represents them with the forward slash (/) as the path separator. This representation is named POSIX style.
๐ŸŒ
Vultr
docs.vultr.com โ€บ python โ€บ examples โ€บ get the file name from the file path
Python Program to Get the File Name From the File Path
April 10, 2025 - Extracting a filename from a file path in Python is essential for file operations, system administration, and data processing tasks. The os module provides os.path.basename(), a straightforward method for filename extraction, while the pathlib module offers a more modern, object-oriented way to handle file paths in Python.
๐ŸŒ
Python Cheat Sheet
pythoncheatsheet.org โ€บ home โ€บ file directory path
File and directory Paths - Python Cheat Sheet
There are two main modules in Python that deals with path manipulation. One is the os.path module and the other is the pathlib module.
๐ŸŒ
FavTutor
favtutor.com โ€บ blogs โ€บ get-filename-from-path-python
03 Methods to Get Filename from Path in Python (with code)
December 16, 2022 - Learn how to get filename from path in python with code. Extract or Read the filename with extension using OS & pathlib module, or split function.
๐ŸŒ
Alemoh Rapheal Baja
alemsbaja.hashnode.dev โ€บ demystifying-python-paths-a-comprehensive-guide-to-the-path-module-for-effortless-file-and-directory-management
Python path, pathlib in Python, os.path in Python
January 25, 2024 - The following are the methods under the OS path module in Python. The os.path.basename() method in is used to access the file or folder name on the last part of the pathname after the last forward-slash.