我的Python脚本所在的文件夹的路径是什么?

时间:2017-10-16 12:19:11

标签: python python-3.x path operating-system sys

我希望我的Python脚本能够由其他文件夹设置的人运行,因此使用对Python脚本保存的文件夹的引用非常有意义。

示例:如果我的脚本," script_1.py"是从" C:\ My Scripts \ script_1.py"我想保存" C:\ My Scripts"到我可以使用的变量。

然而,我无法将其付诸实践。

我已导入os和sys,但使用os.path.dirname(__file__)os.path.abspath(__file__)会显示错误消息:

Traceback (most recent call last):

File "<ipython-input-24-1830932ce69b>", line 1, in <module>
os.path.dirname(__file__)

NameError: name '__file__' is not defined

使用sys.executable为我提供了安装Python的地址(我认为??它并没有给我提供我无论如何都要寻找的东西)。

我也接受了尝试os.environ['_']的建议,但这给出了:

Traceback (most recent call last):

File "<ipython-input-26-6c75f8b10c6d>", line 1, in <module>
os.environ['_']

File "D:\Continuum\Anaconda3\lib\os.py", line 669, in __getitem__
   raise KeyError(key) from None

KeyError: '_'

我顺便从Windows 10运行我的代码。这是Python 3。

1 个答案:

答案 0 :(得分:1)

这将为您提供脚本的位置。

import os
import sys
script_location = os.path.split(os.path.realpath(sys.argv[0]))[0]