![How Can I Get the Full Path of the Current Python Script's Directory?](https://img.php.cn/upload/article/000/000/000/173372569859472.jpg)
获取当前文件的完整目录路径
要检索包含当前Python脚本的目录的完整路径,有几种利用Python模块的方法,例如pathlib 和 os.path。
Python 3
运行目录脚本:
import pathlib
pathlib.Path(__file__).parent.resolve()
当前工作目录:
import pathlib
pathlib.Path().resolve()
Python 2 和 3
运行脚本的目录:
import os
os.path.dirname(os.path.abspath(__file__))
对于当前的工作目录:
import os
os.path.abspath(os.getcwd())
参考文献:
- [pathlib 的 Python 文档](https://docs.python.org/3/library/pathlib .html)
- [os.path 文档 (Python 2.7)](https://docs.python.org/2/library/os.path.html)
- [os.path 文档 (Python 3)](https://docs.python.org /3/library/os.path.html)
- [os.getcwd 文档 (Python 2.7)](https://docs.python.org/2/library/os.path.html#os.getcwd)
- [os.getcwd 文档 (Python 3)](https://docs .python.org/3/library/os.path.html#os.getcwd)
- [的含义文件 Python 中的变量](https://stackoverflow.com/questions/3430370/what-does-the-file-variable-mean-do)
以上是如何获取当前Python脚本目录的完整路径?的详细内容。更多信息请关注PHP中文网其他相关文章!