文件位于同一文件夹中,但仍获取FileNotFoud

2024-06-16 11:54:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图通过Pickle打开一个.dat文件。虽然该文件与我的.py文件位于同一文件夹中,但当我运行时,会出现FileNotFoundError。 (仅供参考:我正在使用VScode运行该文件,但是,当我使用Terminal时,它运行得非常好)

这是我的密码

import pickle

websites_list = pickle.load(open("websites.dat","rb"))
print(websites_list)

这是.py路径:

/Users/lequangdang/Documents/WSC/WSC_2.0/changewebsiteGUI.py

下面是.dat路径:/Users/lequangdang/Documents/WSC/WSC_2.0/websites.dat

以下是错误:

FileNotFoundError: [Errno 2] No such file or directory: 'websites.dat'

Tags: 文件py路径文件夹userspickledocumentslist
1条回答
网友
1楼 · 发布于 2024-06-16 11:54:20

使用vscode时,相对路径基于工作目录,但使用terminal时,相对路径基于py文件本身

例如,目录结构如下所示:

WSC -WSC2.0 -changewebsiteGUI.py

当您在vscode中打开WSC时,pickle.load(open("websites.dat","rb"))将调用路径WSC/websites.dat,这就是为什么您有FileNotFoundError

解决此问题的一种方法是设置vscodelaunch.json,添加以下行:

"cwd": "${workspaceRoot}/WSC2.0"

另一种方法是使用一些函数来获取pyfile本身的abs路径:

os.path.dirname(os.path.abspath(__file__))

相关问题 更多 >