Exception has occurred: FileNotFoundError [Errno 2] No such file or directory: 'data.json'

Question:

Help me fix the problem.’data.json‘ is in the same directory as my python script but when I run the program I get the following error

Exception has occurred: FileNotFoundError [Errno 2] No such file or directory: ‘data.json’

import json

data = json.load(open("data.json))

def translate(w):
    return data[w]

word = input("Enter word: ")

print(translate(word))
Asked By: kelvinmacharia254

||

Answers:

it depends on the folder where you are running the script, not the script folder.

For get the real path to the directory where your script are, you can use it :

import os 
dir_path = os.path.dirname(os.path.realpath(__file__))

open(dir_path + '/' + 'data.json')
Answered By: iElden

After further research. I noticed that the catch here is to explore python’s os module. Tutorials are available online from the various site.OS module helps your program communicate with the underlying Operating system. Issues I had raised are handled explicitly by the OS module.

Answered By: kelvinmacharia254

To solve the problem you must move the data.json file out of the the python script folder,and then run the program.

Your code is perfectly fine.

Answered By: Harsh Garg
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.