gpt4 book ai didi

python - 文件在同一个文件夹中,但仍然得到 FileNotFoud

转载 作者:行者123 更新时间:2023-12-04 08:02:38 27 4
gpt4 key购买 nike

我正在尝试通过 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'

最佳答案

相对路径在使用 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__))

关于python - 文件在同一个文件夹中,但仍然得到 FileNotFoud,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66378837/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com