Home >Backend Development >Python Tutorial >How to Extract a Filename Without Extension in Python?

How to Extract a Filename Without Extension in Python?

Linda Hamilton
Linda HamiltonOriginal
2025-01-03 00:26:39542browse

How to Extract a Filename Without Extension in Python?

Getting Filename without Extension from a Path in Python

In Python, there are various methods to retrieve the filename without the extension from a given path. This task can be achieved using techniques in both Python 3.4 and earlier versions. Here are the approaches:

Python 3.4 and Above

The pathlib.Path.stem attribute provides a convenient solution:

from pathlib import Path
Path("/path/to/file.txt").stem
# Output: 'file'

Python Versions Prior to 3.4

For Python versions before 3.4, a combination of os.path.splitext() and os.path.basename() can be employed:

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

The os.path.basename() function extracts the filename from the path, while os.path.splitext() splits the filename into its name and extension. The [0] index retrieves the filename without the extension.

The above is the detailed content of How to Extract a Filename Without Extension in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn