设置
我在计算机上运行脚本,该脚本位于目录 Users/path/to/my/script.py 中.
I run a script on my computer, located in the directory Users/path/to/my/script.py.
在脚本中,我使用了脚本的路径,例如
In the script, I use the path to the script, e.g.,
sub_path = 'Users/path/to/my/' os.chdir(sub_path + 'other_script/')如您所见,我在手动"代码中定义了 sub_path .
As you can see, I define sub_path in the code 'manually'.
问题
我不想手动定义 sub_path ,我希望Python为我做.
I don't want to define the sub_path manually, I'd rather have Python do it for me.
我正在寻找与用于获取当前工作目录的代码相似的东西: os.getcwd(),然后是用于获取当前文件目录的代码.
I'm looking for something similar to the code I use to obtain the current working directory: os.getcwd(), but then a code to obtain the directory of the current file.
我主要找到的答案与这个类似,
I mainly find answers similar to this one, which says,
os.path.abspath(os.path.dirname(__ file __))
但在Spyder&Anaconda设置,这会生成 NameError:名称'__file__'未定义.
but in the Spyder & Anaconda set-up, this generates a NameError: name '__file__' is not defined.
我该怎么办?
推荐答案如果要移回一个文件夹/目录,请在文件路径中使用 .. .
You if you want to move back one folder/directory you use the .. in your file path.
os.chdir('../other_scripts/')
将起作用.您可能认为查看此或 Wiki .如果要从当前位置移走,可以使用'./new_dir/'.如果您想自动查找其他文件,可以在此处中阅读使用 os.walk .这可能是同一问题.
will work. You may fine it helpful to view this or the wiki. If you want to move from where you currently are you can use './new_dir/'. If you want to automate how to find other files you may want to read here which says to use os.walk. This may be the same question.
更多推荐
如何在Spyder(Anaconda)中找到当前.py文件的路径?
发布评论