Question

Get a Filename Without Its Extension from a Path in Python

pythonstringpath

Question

How can I get the filename without its extension from a file path in Python?

For example:

path = "/path/to/some/file.txt"

I want the result to be:

"file"

Short Answer

By the end of this page, you will understand how to extract just the filename stem from a full file path in Python. You will learn the most common approaches using pathlib and os.path, see how they behave with different filenames, and understand which option is usually best in modern Python code.

Concept

In Python, a file path often contains several parts:

  • directories: /path/to/some/
  • filename: file.txt
  • extension: .txt

When you want only the filename without its extension, you are usually looking for the file's stem.

This matters because many programs need to:

  • generate output filenames
  • display a clean name to users
  • group files by base name
  • rename or transform files
  • process uploaded files safely

Python gives you two common ways to do this:

  • pathlib, which is the modern, object-oriented approach
  • os.path, which is the older but still widely used approach

For most new Python code, pathlib is the clearest choice.

A key detail: removing an extension is not the same as removing text manually. File paths can be tricky because:

  • different operating systems use different path styles
  • some files have multiple dots, like archive.tar.gz
  • some files have no extension at all
  • hidden files on Unix may start with a dot, like .env

Using Python's path tools is safer and clearer than splitting strings by hand.

Mental Model

Think of a file path like a mailing address:

  • the folders are the street and city
  • the filename is the recipient
  • the extension is a label attached to the name

If the full path is:

"/path/to/some/file.txt"

then:

  • /path/to/some/ is the location
  • file.txt is the full filename
  • file is the core name you want
  • .txt is the extension

Your job is to ask Python: "Give me the name part, but leave off the extension label."

Take Quiz

Syntax and Examples

The modern Python way is to use pathlib.

Using pathlib

from pathlib import Path

path = Path("/path/to/some/file.txt")
name_without_extension = path.stem

print(name_without_extension)

Output:

file

Why this works

  • Path(...) turns the string into a path object
  • .stem returns the filename without the final extension

Using os.path

import os

path = "/path/to/some/file.txt"
filename = os.path.basename(path)
name_without_extension = os.path.splitext(filename)[0]

print(name_without_extension)

Output:

file

Why this works

  • os.path.basename(path) gets file.txt
  • os.path.splitext(...) splits it into:
    • filename part: file
    • extension part: .txt
  • [0] selects the filename part

More examples

from pathlib import Path

print(Path("/docs/report.pdf").stem)      # report
print(Path("/tmp/archive.tar.gz").stem)   # archive.tar
print(Path("notes").stem)                 # notes
print(Path(".env").stem)                  # .env

Notice this important behavior:

  • archive.tar.gz becomes archive.tar because only the last extension is removed
  • notes stays notes because there is no extension
  • .env stays .env because it is treated as a hidden filename, not a normal extension-based file

Step by Step Execution

Consider this example:

from pathlib import Path

path = Path("/path/to/some/file.txt")
result = path.stem
print(result)

Here is what happens step by step:

  1. Python imports Path from the pathlib module.
  2. Path("/path/to/some/file.txt") creates a path object representing that file path.
  3. path.stem asks for the filename without its final extension.
  4. Python looks at the last part of the path, which is file.txt.
  5. It removes the final extension .txt.
  6. The result becomes file.
  7. print(result) outputs:
file

Traceable example with multiple paths

from pathlib import Path

paths = [
    "/a/b/photo.jpg",
    "/a/b/archive.tar.gz",
    "/a/b/readme",
]

for p in paths:
    path = Path(p)
    print(path.name, "->", path.stem)

Output:

photo.jpg -> photo
archive.tar.gz -> archive.tar
readme -> readme

This shows that .stem removes only the last extension.

Real World Use Cases

This concept appears often in real programs.

Common uses

  • Batch file processing: read all .csv files and create output files using the same base name
  • Image conversion: turn photo.png into photo.jpg
  • Upload systems: display a clean filename to users without the extension
  • Report generation: convert report.docx into report.pdf
  • Logging and exports: derive related filenames like data.json → data_backup.json

Example: creating an output filename

from pathlib import Path

input_path = Path("/images/photo.png")
output_name = input_path.stem + ".jpg"

print(output_name)

Output:

photo.jpg

Example: labeling imported files

from pathlib import Path

files = [
    "/uploads/alice_resume.pdf",
    "/uploads/project_notes.txt",
]

for file_path in files:
    print(Path(file_path).stem)

Output:

alice_resume
project_notes
Take Quiz

Real Codebase Usage

In real projects, developers usually do not split file paths manually. They rely on pathlib or os.path because those tools are clearer and handle edge cases better.

Common patterns

1. Build derived filenames

from pathlib import Path

source = Path("report.csv")
backup = source.with_name(source.stem + "_backup.csv")

print(backup)

This pattern is useful when generating related files.

2. Validate before processing

from pathlib import Path

path = Path("invoice.pdf")

if path.suffix != ".pdf":
    raise ValueError("Expected a PDF file")

print(path.stem)

This is a simple validation pattern.

3. Process many files in a loop

from pathlib import Path

for path in Path("data").glob("*.json"):
    print(path.stem)

This is common in scripts and data pipelines.

4. Guard against empty or invalid input

from pathlib import Path

file_path = ""

if not file_path:
    print("No file path provided")
else:
    print(Path(file_path).stem)

This is a basic guard clause pattern.

Why pathlib is common in modern code

  • more readable than nested os.path calls
  • path operations are grouped on one object
  • works well with loops, globbing, renaming, and file operations
  • easier to maintain in larger codebases

Common Mistakes

Beginners often try to solve this as a plain string problem. That can work sometimes, but it often breaks on edge cases.

Mistake 1: Splitting on /

Broken example:

path = "/path/to/some/file.txt"
name = path.split("/")[-1].split(".")[0]
print(name)

Why this is risky:

  • assumes / is the separator
  • breaks more easily with unusual filenames
  • becomes hard to read

Better:

from pathlib import Path

print(Path(path).stem)

Mistake 2: Removing everything after the first dot

Broken example:

filename = "archive.tar.gz"
name = filename.split(".")[0]
print(name)

Output:

archive

Why this is wrong:

  • it removes too much
  • many files have multiple dots

Better:

from pathlib import Path

print(Path("archive.tar.gz").stem)

Output:

archive.tar

Mistake 3: Confusing .name, .stem, and .suffix

from pathlib import Path

path = Path("/tmp/file.txt")

print(path.name)    # file.txt
print(path.stem)    # file
print(path.suffix)  # .txt

Use the right property for the job.

Mistake 4: Expecting all extensions to disappear

from pathlib import Path

print(Path("archive.tar.gz").stem)

Output:

archive.tar

If you want to remove all suffixes, you need extra logic.

Mistake 5: Treating hidden files as normal extensions

from pathlib import Path

print(Path(".env").stem)

Output:

.env

This is correct behavior. .env is usually a hidden filename, not a filename "" with extension .env.

Comparisons

pathlib vs os.path

ApproachExampleStyleBest for
pathlibPath(path).stemModern, object-orientedMost new Python code
os.pathos.path.splitext(os.path.basename(path))[0]Older, function-basedExisting codebases using os.path

.name vs .stem vs .suffix

PropertyExample result for /tmp/file.txtMeaning
.namefile.txtFull filename
.stemfileFilename without final extension
.suffix.txtFinal extension

Remove final extension vs remove all extensions

FilenameFinal extension removedAll extensions removed
file.txtfilefile
archive.tar.gzarchive.tararchive
notesnotesnotes

If you only need the usual filename stem, use .stem. If you need to strip all suffixes from names like archive.tar.gz, you need custom logic.

Take Quiz

Cheat Sheet

Quick reference

Modern approach

from pathlib import Path

Path("/path/to/file.txt").stem
# file

Older approach

import os

os.path.splitext(os.path.basename("/path/to/file.txt"))[0]
# file

Useful pathlib properties

from pathlib import Path

p = Path("/path/to/file.txt")

p.name    # file.txt
p.stem    # file
p.suffix  # .txt
p.parent  # /path/to

Important rules

  • .stem removes only the last extension
  • files with no extension return their full name
  • hidden files like .env stay .env
  • prefer pathlib in modern Python code
  • avoid manual string splitting for paths

Edge cases

from pathlib import Path

Path("archive.tar.gz").stem  # archive.tar
Path("notes").stem           # notes
Path(".env").stem            # .env

FAQ

How do I get a filename without extension in Python?

Use pathlib:

from pathlib import Path
Path("/path/to/file.txt").stem

This returns file.

What is the difference between stem and name in Python?

  • name gives the full filename, such as file.txt
  • stem gives the filename without the final extension, such as file

Does Path.stem remove all extensions?

No. It removes only the final extension.

from pathlib import Path
print(Path("archive.tar.gz").stem)
# archive.tar

Should I use pathlib or os.path?

For new code, pathlib is usually easier to read and use. os.path is still fine, especially in older codebases.

What happens if the file has no extension?

The name is returned unchanged.

from pathlib import Path
print(Path("README").stem)
# README

How do hidden files like .env behave?

They are usually treated as filenames, not normal extension-based files.

from pathlib import Path
print(Path(".env").stem)
# .env

Can I use this on Windows paths too?

Yes. Python path tools are designed to work with path handling across operating systems. pathlib is especially convenient for this.

Take Quiz

Mini Project

Description

Build a small Python utility that takes a list of file paths and prints a clean report showing each original path, its filename, and its filename without the extension. This demonstrates practical path parsing and helps reinforce the difference between full paths, names, and stems.

Goal

Create a script that extracts filename stems from multiple file paths using pathlib.

Requirements

  • Create a list containing at least four file paths
  • For each path, display the full filename and the filename without the extension
  • Use pathlib.Path in the solution
  • Include at least one file with multiple dots and one file with no extension
Take Quiz

Keep learning

Related questions

View more