IOError: [Errno 2] No such file or directory: 'data.json' IO错误:[错误编号2] 没有此文件或目录:'data.json'

4

这是我的代码:

import json
from difflib import get_close_matches
data = json.load(open("data.json")) # I get an error here
def translate(w):
    w = w.lower()
    if w in data:
        return data[w]
        elif len(get_close_matches(w, data.keys())) > 0:
        yn = input("Did you mean %s instead? Enter Y if yes, or N if no: " % get_close_matches(w, data.keys())[0])
        if yn == "Y":
            return data[get_close_matches(w, data.keys())[0]]
        elif yn == "N":
            return "The word doesn't exist. Please double check it."
        else:
            return "We didn't understand your entry."
    else:
        return "The word doesn't exist. Please double check it."

word = input("Enter word: ")
output = translate(word)
if type(output) == list:
    for item in output:
        print(item)
else:
    print(output)

在这行代码中:data = json.load(open("data.json")),我收到了以下错误消息:

IOError: [Errno 2] No such file or directory: 'data.json'

我该如何修复这个错误呢?请确保文件名为"data.json"的文件存在于正确的路径下。

2
你需要在 data = json.load(open("完整的json文件路径")) 中提到你的json文件的物理位置。 - Rakesh
请问能否提供错误信息? - costrouc
2
错误信息告诉您在当前目录(启动Python的位置)中没有名为“data.json”的文件。 - llllllllll
@liliscent,虽然抢先发表很诱人,但我建议你将其作为答案发布,并包括这样一个事实:如果运行程序的用户没有读取data.json的权限,他们可能会看到相同的错误。 - Philip Adler
1
@PhilipAdler 或许你可以添加一个答案。但是据我所知,如果您没有读取该文件的权限,则错误应为“权限被拒绝”,而不是“找不到文件”。 - llllllllll
1个回答

1
正如错误信息所提示的那样,在运行程序的目录中没有名为"data.json"的文件。如果您明确使用文件的完整路径,则程序应该可以工作。

与pandas的.to_csv方法不同,它可以使用相对路径,但是似乎open需要从根目录/开始的完整路径。 - yeliabsalohcin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接