In Python 3.4+, you can use the pathlib module (included in Python's standard library):

>>> from pathlib import Path
>>> p = Path("/home/user/Downloads/repo/test.txt")
>>> print(p.stem)
test
>>> print(p.name)
test.txt
Answer from smheidrich on Stack Overflow
🌐
Python
docs.python.org › 3 › library › pathlib.html
pathlib — Object-oriented filesystem paths
Source code: Lib/pathlib/ This module offers classes representing filesystem paths with semantics appropriate for different operating systems. Path classes are divided between pure paths, which pro...
People also ask

What is the pathlib equivalent of basename()?
Use Path(path).name when the surrounding code uses pathlib; Path.name exposes the final component as a property.
🌐
pythonpool.com
pythonpool.com › home › tutorials › python os.path.basename(): files, trailing slashes, and pathlib
Python os.path.basename(): Files, Trailing Slashes, and pathlib
What does os.path.basename() return?
It returns the final component of a pathname string, such as a filename, without checking whether the path exists.
🌐
pythonpool.com
pythonpool.com › home › tutorials › python os.path.basename(): files, trailing slashes, and pathlib
Python os.path.basename(): Files, Trailing Slashes, and pathlib
How do I remove a file extension after basename()?
Extract the final component first, then use os.path.splitext() or Path.stem and Path.suffix according to the project path style.
🌐
pythonpool.com
pythonpool.com › home › tutorials › python os.path.basename(): files, trailing slashes, and pathlib
Python os.path.basename(): Files, Trailing Slashes, and pathlib
🌐
Python.org
discuss.python.org › ideas
Clarify if os.path.basename is equivalent to pathlib.Path.name - Ideas - Discussions on Python.org
October 15, 2024 - within the documentation the table tells us that os.path.basename() is equivalent to PurePath.name however, this SO thread states According to the Python documentation os.path.basename simply uses .split(). It therefore is a fairly rudimentary implementation.
🌐
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 - Python provides built-in modules ... and the pathlib module. Using os.path.basename The os module has a function called basename() that returns the final component of a path....
🌐
GeeksforGeeks
geeksforgeeks.org › python › get-filename-from-path-without-extension-using-python
Get filename from path without extension using Python - GeeksforGeeks
October 3, 2025 - Python · import pathlib path = ... extension. Works uniformly on Windows/macOS/Linux. ntpath.basename() pulls out the filename regardless of platform, then rfind('.') locates the final dot....
🌐
Astral
docs.astral.sh › ruff › rules › os-path-basename
os-path-basename (PTH119) | Ruff - Astral Docs
When possible, using Path object ... os.path.basename()). ... While using pathlib can improve the readability and type safety of your code, it can be less performant than the lower-level alternatives that work directly with strings, especially on older versions of Python...
Find elsewhere
🌐
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 Pool
pythonpool.com › home › tutorials › python os.path.basename(): files, trailing slashes, and pathlib
Python os.path.basename(): Files, Trailing Slashes, and pathlib
July 13, 2026 - The practical rule is to use os.path.basename() for string paths, normalize first when trailing separators should be ignored, and prefer Path.name when the surrounding code already uses pathlib.
🌐
Medium
medium.com › @ryan_forrester_ › understanding-pythons-basename-complete-guide-7730ea4235fb
Understanding Python’s basename: Complete Guide | by ryan | Medium
November 5, 2024 - Working with file paths in Python isn’t always straightforward, especially when you need to extract specific parts of a path. That’s where basename comes in — it’s a straightforward way to get the final component of a file path.
🌐
FavTutor
favtutor.com › blogs › get-filename-from-path-python
03 Methods to Get Filename from Path in Python (with code)
December 16, 2022 - import os file_path = ... different operating systems. Inside the pathlib library, we can use the Path function to get the filename from a given path....
🌐
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 - Since directory_path here ends with a slash, os.path.basename() returns an empty string, highlighting the importance of validating paths when extracting filenames in Python. Import the pathlib module, which provides object-oriented file path ...
🌐
eSparkBiz
esparkinfo.com › path from any os/path format
How to Extract File Name from Path in Python Easily?
July 30, 2025 - Learn how to extract file names from full paths in Python using os.path and pathlib. Works seamlessly on Windows, Linux, and macOS with no changes. ... Scalable, Secure, and High-Performance Solutions for Your Business. ... In Python, you can extract just the filename from a full path using either os.path.basename() or pathlib.Path().name.
🌐
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.
🌐
Amit Chaudhary
amitness.com › posts › pathlib-cheatsheet
Migrating from OS.PATH to PATHLIB Module in Python
December 29, 2019 - from pathlib import Path Path('key.pem').chmod(0o400) import os os.path.basename('/home/ubuntu/hello.py') # hello.py · from pathlib import Path Path('/home/ubuntu/hello.py').name # hello.py ·
🌐
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.
🌐
Python
docs.python.org › 3 › library › os.path.html
os.path — Common pathname manipulations
This is the second element of the pair returned by passing path to the function split(). Note that the result of this function is different from the Unix basename program; where basename for '/foo/bar/' returns 'bar', the basename() function ...
🌐
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.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-program-to-get-the-file-name-from-the-file-path
Python Program to Get the File Name From the File Path - GeeksforGeeks
July 23, 2025 - import os file_path = 'C:/Users/test.txt' file_name = os.path.basename(file_path) file = os.path.splitext(file_name) print(file) # returns tuple of string print(file[0] + file[1]) ... The Python Pathlib package offers a number of classes that describe file system paths with semantics suitable for many operating systems.
🌐
Bacancy Technology
bacancytechnology.com › qanda › python › extract-file-name-from-path-from-any-os-path-format
How to Extract File Name from Path Across Any OS/Path Format
January 17, 2025 - os.path.basename() is cross-platform, which makes it a reliable choice for file name extraction in Python. It takes care of the differences between path formats and works seamlessly on both UNIX-like systems (Linux/macOS) and Windows.