In Python coding, acquiring the full directory path of the file being executed can be a crucial task. This question explores this topic, specifically aiming to extract the directory path while excluding the filename.
The user has attempted to utilize the os.path.abspath(__file__) function to retrieve the file's absolute path. However, this approach yields the complete path, including the filename. The desired output is to obtain the directory path alone.
To resolve this challenge, Python offers multiple solutions:
Python 3
For the Directory of the Running Script:
import pathlib pathlib.Path(__file__).parent.resolve()
For the Current Working Directory:
import pathlib pathlib.Path().resolve()
Python 2 and 3
For the Directory of the Running Script:
import os os.path.dirname(os.path.abspath(__file__))
For the Current Working Directory:
import os os.path.abspath(os.getcwd())
The above is the detailed content of How to Get Only the Directory Path from a File's Absolute Path in Python?. For more information, please follow other related articles on the PHP Chinese website!