设置
我在我的计算机上运行一个脚本,位于Users/path/to/my/script.py
目录中。
在脚本中,我使用脚本的路径,例如,
sub_path = 'Users/path/to/my/'
os.chdir(sub_path + 'other_script/')
如您所见,我在代码“手动”中定义了sub_path
。
问题
我不想手动定义sub_path
,我宁愿让Python来帮我。
我正在寻找类似于我用于获取当前工作目录的代码:os.getcwd()
,但接下来是获取当前文件目录的代码。
我主要发现的答案类似于这一个,它说,
os.path.abspath(os.path.dirname(__file__))
但是在Spyder & Anaconda设置中,这会生成一个NameError: name '__file__' is not defined
。
我能做什么?
发布于 2018-05-07 15:20:57
发布于 2021-04-17 15:07:39
Mark8888 指出来运行整个脚本(运行文件(F5)),而不是只运行脚本的一部分
通过这种方式,多种方法应该可以获得脚本文件的位置并更改当前的工作目录。
import os
# directory of script file
print(os.path.abspath(os.path.dirname(__file__)))
# change current working directory
os.chdir(os.path.abspath(os.path.dirname(__file__)))
# current working directory
print(os.getcwd())
也是
import os
import sys
# directory of script file
print(os.path.abspath(os.path.dirname(sys.argv[0])))
# change current working directory
os.chdir(os.path.abspath(os.path.dirname(sys.argv[0])))
# current working directory
print(os.getcwd())
发布于 2018-05-07 17:27:27
我在运行的任何脚本中添加以下行,以防需要访问相对于脚本位置的数据
import sys
script = sys.argv[0]
print(script)
'C:/SomeFolder/A_Subfolder/CurrentlyRunningScript.py' # changed obviously
https://stackoverflow.com/questions/50216508
复制相似问题