python 相对路径FileNotFoundError: [Errno 2] No such file or directory: 'nihao.txt'

问题遇到的现象和发生背景

macOS Monterey12.3
python3.10

一开始atom里面的atom-python-run不能运行,修改F5 command 为 python3 {file}之后可以运行程序了,但是在打开相对路径的程序时报错。

经测试cd到文件夹里可以正常运行,但是通过路径打开时报错FileNotFoundError: [Errno 2] No such file or directory: 'nihao.txt'

img


py程序与txt文件在一个文件夹里

问题相关代码,请勿粘贴截图

x=open('nihao.txt')
print(x)

运行结果及报错内容

img


通过路径打开时报错

img


cd到文件夹里正常

我想要达到的结果

在不改变程序的情况下有没有通过改变mac的设置使程序运行

你是直接运行的ceshi.py文件吗?
你把这个目录加上试试

img

是不是你的路径搞错啦?提示的是找不到这个文件

你可以参考下这篇文章:python中:FileNotFoundError: [Errno 2] No such file or directory: