0

I have a folder named study in which I have a JSON file named data.json but when I'm trying to open it in a python script located in the same folder, I get FileNotFoundError: [Errno 2] No such file or directory: 'data.json'.

When I use the full, absolute path to data.json, however, it works.

How do I fix this such that I can specify the path of data.json to be in the same folder as my .py file?

Here is my code:

import json

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

def translate(w):
    return data[w]

word = input("Enter word: ")

print(translate(word))

Jean-François Corbett
  • 36,032
  • 27
  • 135
  • 183

1 Answers1

4

Use __file__. This will enable you to specify paths that are relative to the location of your Python script file.

import os

data_file_path = os.path.join(os.path.dirname(__file__), "data.json")
data = json.load(open(data_file_path))

Alternatively, using pathlib instead of os:

from pathlib import Path

data_file_path = Path(__file__).parent / "data.json"
data = json.load(open(data_file_path))
Jean-François Corbett
  • 36,032
  • 27
  • 135
  • 183