首页 > 解决方案 > 如何在 Spyder (Anaconda) 中找到当前 .py 文件的路径?

问题描述

设置

我在我的计算机上运行一个脚本,位于目录中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.

我能做些什么?

标签: pythonanacondaspyder

解决方案


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())

推荐阅读