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

How to Get a Filename Without Its Extension in Python?

Mary-Kate Olsen
Release: 2024-12-14 20:59:12
Original
843 people have browsed it

How to Get a Filename Without Its Extension in Python?

Retrieving Filename without Extension from a Path in Python

Determining the filename excluding its extension is a common task when working with paths. In Python, achieving this can be accomplished in several ways.

Python 3.4 and Above

Leveraging the pathlib module's stem attribute provides a straightforward approach for retrieving the filename without the extension:

from pathlib import Path

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

print(filename_without_extension)  # Outputs: "file"
Copy after login

Python Versions Prior to 3.4

For Python versions before 3.4, a combination of the os.path.splitext and os.path.basename functions can be utilized:

import os.path

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

filename = os.path.basename(path)
filename_without_extension = os.path.splitext(filename)[0]

print(filename_without_extension)  # Outputs: "file"
Copy after login

This approach ensures compatibility with older Python versions while achieving the objective of extracting the filename without the extension.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template