DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk2 min

How to Get a Filename from a Path in Python

Use pathlib’s Path.name for the final component of a path, or os.path.basename() in string-based code. Learn how trailing separators, Windows paths, and suffixes affect the result.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Path(path).name to get the final component of a path in modern Python code. For example, Path("/home/user/report.csv").name returns report.csv. If your code works with path strings and already uses os, os.path.basename(path) does the same for ordinary paths.

Get the filename with pathlib

Path.name returns the final path component, including its extension, while excluding the drive and root. The Python documentation describes Path as the likely choice if you are unsure which pathlib class to use. See the Python 3.14 pathlib documentation.

from pathlib import Path

filename = Path("/home/user/report.csv").name
print(filename)  # report.csv

This extracts a name lexically; it does not check whether the path exists or whether its final component is a file.

Use os.path for string-based code

os.path.basename(path) is the direct string-path function for returning the final component. It also accepts path-like objects starting with Python 3.6. The pathlib documentation maps this function to PurePath.name, so choose the style that fits the rest of your code.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import os

filename = os.path.basename("/home/user/report.csv")
print(filename)  # report.csv

Account for trailing separators

A trailing separator changes the result from os.path.basename(): os.path.basename('/foo/bar/') returns an empty string, not bar. This differs from the Unix basename command. The behavior is documented in the Python os.path reference.

If your input may end in a separator and you want to ignore it, choose and apply a normalization policy before extracting the component; do not assume basename() always returns a non-empty name. Paths that end at a root or a Windows share can also have no final name component.

Parse Windows path text on any operating system

Path parsing normally follows the conventions of the host operating system. If you are processing Windows-formatted text on a non-Windows machine, use PureWindowsPath to parse that syntax without accessing the filesystem:

from pathlib import PureWindowsPath

filename = PureWindowsPath(r"C:UsersAdareport.csv").name
print(filename)  # report.csv

A pure path represents path syntax only; it does not establish that the represented path exists. For the path classes and their behavior, see the pathlib documentation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Get the extension separately

Use Path.suffix for the final suffix and Path.stem for the final component without that suffix:

from pathlib import Path

path = Path("archive.tar.gz")
print(path.name)    # archive.tar.gz
print(path.suffix)  # .gz
print(path.stem)    # archive.tar

suffix is only the last dot-separated suffix, not every extension-like part of the name. The pathlib reference documents these properties.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choose the right expression

Situation Expression Why
Code already uses pathlib Path(path).name Reads the final component through a path object.
Existing string-oriented code os.path.basename(path) Direct function for extracting a path’s final component.
Windows path text on a non-Windows host PureWindowsPath(path).name Explicitly parses Windows path syntax without filesystem access.
Need the final suffix or name without it Path(path).suffix or Path(path).stem Separates the final suffix from the final component.

For names and extensions, these are path-parsing operations, not file checks. If you need to know whether a path currently points to a file, check that separately with Path(path).is_file().

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.