如何在Spyder(Anaconda)中找到当前.py文件的路径?

编程入门 行业动态 更新时间:2024-10-10 23:19:13
本文介绍了如何在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/')

将起作用.您可能认为查看此或 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文件的路径?

本文发布于:2023-11-08 20:47:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1570414.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路径   文件   中找到   如何在   Spyder

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!