Obtaining the Full Directory Path of the Current File
To retrieve the complete path of the directory containing the current Python script, there are several approaches utilizing Python modules such as pathlib and os.path.
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())
References:
- [Python documentation on pathlib](https://docs.python.org/3/library/pathlib.html)
- [os.path documentation (Python 2.7)](https://docs.python.org/2/library/os.path.html)
- [os.path documentation (Python 3)](https://docs.python.org/3/library/os.path.html)
- [os.getcwd documentation (Python 2.7)](https://docs.python.org/2/library/os.path.html#os.getcwd)
- [os.getcwd documentation (Python 3)](https://docs.python.org/3/library/os.path.html#os.getcwd)
- [Meaning of the file variable in Python](https://stackoverflow.com/questions/3430370/what-does-the-file-variable-mean-do)
The above is the detailed content of How Can I Get the Full Path of the Current Python Script's Directory?. 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