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
February 23, 2026 - os.walk() always follows symlinks when categorizing paths into dirnames and filenames, whereas Path.walk() categorizes all symlinks into filenames when follow_symlinks is false (the default.) The pathlib.types module provides types for static type checking. Added in version 3.14.
Discussions

python - How to get folder name, in which given file resides, from pathlib.path? - Stack Overflow
I've noticed pathlib is just a ... to using pathlib and still have this particular one to work around. I did ask a specific question about this actual issue but a small gang of goblins came out of the woods and hacked it to pieces. Vote to reopen if you wish. 2024-06-04T10:58:16.423Z+00:00 ... I came here looking for something very similar. My solution, based on the above by @larsks, and assuming you want to preserve the entire path except the filename, is to ... More on stackoverflow.com
🌐 stackoverflow.com
python - Extract file name from path, no matter what the os/path format - Stack Overflow
Which Python library can I use to extract filenames from paths, no matter what the operating system or path format could be? For example, I'd like all of these paths to return me c: a/b/c/ a/b/c ... More on stackoverflow.com
🌐 stackoverflow.com
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
‘With’ statement vs ‘pathlib’ method for opening files
There is no pathlib method for opening files. pathlib is, as the name suggests, a library for dealing with paths. It is not in any way an alternative to opening files inside a context manager (with), which is responsible for doing things like cleaning up file handles when you are finished with them. In fact the two work together well, for example: directory = pathlib.Path('dir') file_path = directory / "filename" with file_path.open() as f: ... Maybe you should post an example of what you think has changed? More on reddit.com
🌐 r/learnpython
23
3
April 18, 2024
🌐
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
🌐
FavTutor
favtutor.com › blogs › get-filename-from-path-python
03 Methods to Get Filename from Path in Python (with code)
December 16, 2022 - The code implementation using the ... different operating systems. Inside the pathlib library, we can use the Path function to get the filename from a given 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 os path = ... .split('.', 1)[0] takes the part before the first dot. With pathlib, you wrap your path in Path(path) and read its .stem attribute to get the filename without extension....
🌐
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 | Vultr Docs
April 10, 2025 - This approach is modern and Pythonic for handling file paths. Use pathlib to manipulate file paths in an OS-independent manner. Use stem for the filename without extension and suffix for the extension.
🌐
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 - The standard utility modules for Python include this module. Although stem is one of the utility attributes that enables extracts of the filename from the link without extension if we want an extension with the file we can use name attributes ... from pathlib import Path file_path = 'C:/Users/test.txt' # stem attribute extracts the file # name print(Path(file_path).stem) # name attribute returns full name # of the file print(Path(file_path).name)
Find elsewhere
🌐
Real Python
realpython.com › python-pathlib
Python's pathlib Module: Taming the File System – Real Python
January 11, 2025 - For example, you’ll dive into ... unique filenames. It’s great that pathlib offers so many methods and properties, but they can be hard to remember on the fly. That’s where a cheat sheet can come in handy. To get yours, click the link below: Free Download: Click here to claim your pathlib cheat sheet so you can tame the file system with Python...
🌐
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 - Both Windows and Linux paths are supported by these functions, but using pathlib can help reduce inconsistencies across platforms. Working with file paths is a common requirement in many projects. By using python get filename from path methods such as os.path.basename or pathlib.Path.name, you can manage files more efficiently while keeping your code clean and readable.
🌐
TradingCode
tradingcode.net › python › filename-without-last-extension
Get filename with extension removed: here's how in Python
To get the filename without the last extension from those directory items, here’s what we do: from pathlib import Path # Specify the directory to get the filenames without extension from dir_path = Path(r"C:\Wallpapers") # Loop over all directory ...
🌐
eSparkBiz
esparkinfo.com › path from any os/path format
How to Extract File Name from Path in Python Easily?
January 21, 2026 - ... 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.
Price   $12
Address   1001 - 1009 10th floor City Center 2, Sukan Mall Cross Road, Science City Rd, 380060, Ahmedabad
🌐
datagy
datagy.io › home › file handling › python: get filename from path (windows, mac & linux)
Python: Get Filename From Path (Windows, Mac & Linux) • datagy
February 10, 2023 - You’ll learn how to get the filename form a Python path using the os library, the string .split() method, and the popular pathlib library.
🌐
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 - UNIX (including Mac) uses the slash ... · source: os_path_basename_dirname_split_splitext.py · Use os.path.basename() to get the filename (basename) from a path string....
🌐
NAO IT Systems LLC.
digibeatrix.com › home › file & directory operations › how to get filenames in python: using os, pathlib, and glob with examples
How to Get Filenames in Python: Using os, pathlib, and glob with Examples - Practical Python Programming
November 29, 2025 - from pathlib import Path dir_path = Path("/user/home/document") for file in dir_path.glob("*.txt"): print(file)This code retrieves only .txt files in the specified directory. ... There are many ways to get filenames in Python, but choosing the ...
🌐
TestDriven.io
testdriven.io › tips › 01895f3a-6f68-4790-b4cd-7483d106e63b
Filename pattern matching in Python with pathlib.Path.glob()
You can use pathlib.Path.glob() to list all files matching a given pattern. For example, you can list names of all txt files located inside the same directory as your Python script👇
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › get filename without extension in python
Get Filename Without Extension in Python - Spark By {Examples}
May 31, 2024 - One useful method of pathlib.Path is .stem, which returns the filename without extension as a Python string. # Using the .stem Attribute from pathlib import Path # Convert to path object str_path = 'C://Ali/Base/file.txt' path = Path(str_path) # Get filename without extension filename = path.stem print(filename) # Output: # file
🌐
Switowski
switowski.com › blog › pathlib
Pathlib for Path Manipulations - Sebastian Witowski
It unifies the API for various file manipulation operations that previously required using different Python modules. You no longer need the glob module to search for files matching a pattern, and you also don't need the os module to get the names of their directories. All this functionality can now be found in the pathlib module (of course, you can still use the os or glob modules, if you prefer).
Top answer
1 of 16
1977

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 › @emoome82 › extracting-file-names-without-extensions-in-python-caabe8532f92
Extracting File Names Without Extensions in Python | by civilpy | Medium
July 30, 2024 - # Define a file path file_path = '/path/to/your/file.txt'# Get the file name (with extension) file_name_with_extension = os.path.basename(file_path)# Split the file name and extension file_name, extension = os.path.splitext(file_name_with_extension)print(f'File name (without extension): {file_name}') print(f'Extension: {extension}') ... Python 3.4 and above introduced the pathlib module, which provides object-oriented filesystem path operations.