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"
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"
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!