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:
Discussions

How to get just the file name from a file path.
You may get some benefit from os.path , and in particular os.path.basename() . More on reddit.com
๐ŸŒ r/learnpython
9
3
November 11, 2021
Total Noob - How do I properly refer to a file path in python?
On July 1st, a change to Reddit's API pricing will come into effect. Several developers of commercial third-party apps have announced that this change will compel them to shut down their apps. At least one accessibility-focused non-commercial third party app will continue to be available free of charge. If you want to express your strong disagreement with the API pricing change or with Reddit's response to the backlash, you may want to consider the following options: Limiting your involvement with Reddit, or Temporarily refraining from using Reddit Cancelling your subscription of Reddit Premium as a way to voice your protest. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
๐ŸŒ r/learnprogramming
21
11
June 30, 2023
๐ŸŒ
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.
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.

๐ŸŒ
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.
๐ŸŒ
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.
๐ŸŒ
Python
docs.python.org โ€บ 3.3 โ€บ library โ€บ os.path.html
11.1. os.path โ€” Common pathname manipulations โ€” Python 3.3.7 documentation
Return the longest path prefix (taken character-by-character) that is a prefix of all paths in list. If list is empty, return the empty string (''). Note that this may return invalid paths because it works a character at a time. ... Return the directory name of pathname path.
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.
๐ŸŒ
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
๐ŸŒ
Python
docs.python.org โ€บ 3.4 โ€บ library โ€บ os.path.html
11.2. os.path โ€” Common pathname manipulations โ€” Python 3.4.10 documentation
June 16, 2019 - You should upgrade, and read the Python documentation for the current stable release. ... This module implements some useful functions on pathnames. To read or write files see open(), and for accessing the filesystem see the os module. The path parameters can be passed as either strings, or bytes. Applications are encouraged to represent file names as (Unicode) character strings.
๐ŸŒ
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.
๐ŸŒ
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
๐ŸŒ
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.
๐ŸŒ
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.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnprogramming โ€บ total noob - how do i properly refer to a file path in python?
r/learnprogramming on Reddit: Total Noob - How do I properly refer to a file path in python?
June 30, 2023 -

Hello,

I am trying to write in the path "c:/gpt-2-2/models" into a python code. When I run the code I get a syntax error at the "C:" part. I guess I don't know how to properly write file paths in python. Any help would be appreciated.

๐ŸŒ
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.