IOError:[Errno 2]没有这样的文件或目录:“data.json”

2024-05-15 21:15:43 发布

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

这是我的代码:

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'

我怎样才能纠正这个错误?


Tags: importjsoncloseoutputdatagetreturnif
1条回答
网友
1楼 · 发布于 2024-05-15 21:15:43

如错误消息所示,在运行程序的同一目录中没有名为“data.json”的文件。如果显式地使用文件的完整路径,程序应该可以工作。

相关问题 更多 >