0
0
PythonHow-ToBeginner · 3 min read

How to Get Filename Without Extension in Python

Use os.path.splitext() or pathlib.Path.stem to get a filename without its extension in Python. os.path.splitext(filename)[0] returns the filename without extension, and Path(filename).stem does the same in a modern, object-oriented way.
📐

Syntax

There are two common ways to get a filename without its extension in Python:

  • Using os.path.splitext(): Splits the filename into a tuple (root, extension), where root is the filename without extension.
  • Using pathlib.Path.stem: Returns the filename without the extension as a string, using an object-oriented approach.
python
import os
from pathlib import Path

# Using os.path.splitext
filename = 'example.txt'
name_without_ext = os.path.splitext(filename)[0]

# Using pathlib.Path.stem
path = Path(filename)
name_without_ext_pathlib = path.stem
💻

Example

This example shows how to get the filename without its extension using both os.path.splitext() and pathlib.Path.stem. It prints the results to demonstrate they are the same.

python
import os
from pathlib import Path

filename = 'report.final.pdf'

# Using os.path.splitext
name_without_ext = os.path.splitext(filename)[0]
print('Using os.path.splitext:', name_without_ext)

# Using pathlib.Path.stem
path = Path(filename)
name_without_ext_pathlib = path.stem
print('Using pathlib.Path.stem:', name_without_ext_pathlib)
Output
Using os.path.splitext: report.final Using pathlib.Path.stem: report.final
⚠️

Common Pitfalls

One common mistake is to try to remove the extension by splitting the filename on a dot (.) manually, which can fail if the filename contains multiple dots. For example, splitting report.final.pdf by dot and taking the first part gives report, which is incorrect.

Always use os.path.splitext() or pathlib.Path.stem to handle filenames safely.

python
filename = 'report.final.pdf'

# Wrong way: splitting by dot and taking first part
wrong_name = filename.split('.')[0]
print('Wrong way:', wrong_name)  # Outputs 'report'

# Right way: using os.path.splitext
import os
right_name = os.path.splitext(filename)[0]
print('Right way:', right_name)  # Outputs 'report.final'
Output
Wrong way: report Right way: report.final
📊

Quick Reference

Here is a quick summary of methods to get filename without extension:

MethodDescriptionExample
os.path.splitext(filename)[0]Splits filename and returns part before extensionos.path.splitext('file.txt')[0] -> 'file'
pathlib.Path(filename).stemReturns filename without extension using Path objectPath('file.txt').stem -> 'file'

Key Takeaways

Use os.path.splitext(filename)[0] to safely get filename without extension.
pathlib.Path(filename).stem is a modern, readable alternative.
Avoid manual string splitting on dots to prevent errors with multiple dots.
Both methods handle filenames with multiple dots correctly.
Choose pathlib for new code due to its clarity and object-oriented style.