【问题标题】:File in the same folder but still get FileNotFoud文件在同一个文件夹中,但仍然得到 FileNotFoud
【发布时间】:2021-02-26 01:26:30
【问题描述】:

我正在尝试通过 Pickle 打开一个 .dat 文件。尽管该文件与我的 .py 文件位于同一文件夹中,但当我运行时,我得到了 FileNotFoundError。 (仅供参考:我正在使用 VScode 运行文件,但是,当我使用终端时它运行得非常好)

这是我的代码

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'

【问题讨论】:

  • 改用open("/Users/lequangdang/Documents/WSC/WSC_2.0/websites.dat","rb")
  • 哦,成功了,非常感谢
  • VS Code 有工作目录的概念。相对路径基于工作目录。

标签: python file visual-studio-code pickle


【解决方案1】:

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

例如目录结构如下:

WSC---WSC2.0---changewebsiteGUI.py

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

解决这个问题的一种方法是设置 vscode launch.json,添加这一行:

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

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

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

【讨论】:

  • 天哪,我终于得到了一个清晰的解释,非常感谢,你让我很开心?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-23
  • 1970-01-01
  • 2021-03-24
  • 2018-10-18
  • 2014-03-31
  • 1970-01-01
  • 2017-04-17
相关资源
最近更新 更多