1

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))

2 Answers 2

9

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))
Sign up to request clarification or add additional context in comments.

Comments

0
load_my_file('./file_name.etc')

Explanation: ./ is the local directory. Possible for local and for testing. You could change it later, but ./ and then the file_name is pretty fast to code

It's a regular expression from unix. More info: "What Does ./ Mean In Linux?"

1 Comment

./ is the default location where Python will try to open the file. I don't see how adding it could help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.