打开函数 returns python 上出现 404 错误

open function returns 404 error on python

我正在做一个小的 python 项目,发现自己必须阅读一个 json 文件。我尝试使用在网上找到的这个小脚本,但它给了我一个 404 错误。 我有一个包含 json 文件 (datasets.json) 和 python 文件的文件夹,由于某种原因,找不到 json 文件。

with open('datasets.json', 'r') as file:
    dataset = json.loads(file.read())
    print(dataset)

回溯(最近调用最后):文件 "Desktop/proj/ai/index.py",第 4 行,在打开('datasets.json','r')作为文件:FileNotFoundError:[Errno 2] 没有这样文件或目录:'datasets.json'

问题是相对路径取决于当前目录,当您编译 python 文件时,当前目录不是文件所在的目录。尝试使用绝对路径。您还可以使用 os 模块将相对路径转换为绝对路径。

import os
relativePath = './hello/world.py'
absolutePath = os.path.abspath(relativePath)
print(absolutePath)