Amitabh Baidehi
Amitabh Baidehi

Reputation: 33

How to open file located in same folder as Python script

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

Upvotes: 1

Views: 9025

Answers (2)

sivi
sivi

Reputation: 11144

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?"

Upvotes: 0

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

Upvotes: 9

Related Questions