python - 如何在 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
.
我能做些什么?
解决方案
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())
推荐阅读
- python - 从 Python 中的重复数据集制作字典
- scala - 为什么 Spark approxQuantile 使用 groupBy 超级慢?
- three.js - 如何将纹理应用到立方体
- reactjs - 如何通过改变状态来改变 URL
- c# - API Webrequest 类似于 curl 命令
- android - Expo反应本机应用程序图像在testflight ios上无法正常工作
- javascript - 暗模式下的 Google-Map-React 标记不渲染
- java - 如何在运行时而不是编译时从相对路径引用文件
- java - Java HtmlUnit 无法获取元素
- git - 是否可以在两个 git 服务器之间共享代码?