【问题标题】:IOError: [Errno 2] No such file or directory: 'data.json' [duplicate]IOError:[Errno 2]没有这样的文件或目录:'data.json'[重复]
【发布时间】:2018-06-29 15:34:19
【问题描述】:

这是我的代码:

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] 没有这样的文件或目录:'data.json'

我该如何解决这个错误?

【问题讨论】:

  • 你需要在data = json.load(open("full path to your json"))中提到你的json文件的物理位置
  • 你能给我们错误信息吗?
  • 错误信息告诉你当前目录(你启动 python 的地方)中没有名为“data.json”的文件。
  • @liliscent 很诱人,虽然它是为了偷你的风头——我建议你把它作为答案发布,并包括这样一个事实,即如果运行程序的用户没有读取 data.json 的权限,那他们可能会看到同样的错误。
  • @PhilipAdler 也许你可以添加一个答案。但据我所知,如果您没有读取该文件的权限,则错误应该是“权限被拒绝”,而不是“没有这样的文件”。

标签: python json python-2.7 python-import


【解决方案1】:

正如错误消息所暗示的,在与您运行程序的目录相同的目录中没有名为“data.json”的文件。如果您明确使用文件的完整路径,程序应该可以工作。

【讨论】:

  • 与pandas .to_csv 方法不同,它可以采用相对路径,似乎open 需要一个来自root / 的完整路径。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多