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!