如何在Spyder(Anaconda)中找到当前.py文件的路径? [英] How to find path to current .py file in Spyder (Anaconda)?

查看:728
本文介绍了如何在Spyder(Anaconda)中找到当前.py文件的路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

设置

我在计算机上运行脚本,该脚本位于目录 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/')

将起作用.您可能认为查看此处中阅读使用 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文件的路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆