Python FileNotFoundError :

374 Views Asked by At

I have the below structure

sample.py pack/ -app.py -test.json

sample.py

from pack import app 

app.print_name()

app.py

import json 

def print_name():
    with open(file=r"test.json",mode='r') as json_file :
        py_dict = json.load(json_file)
    print(py_dict["name"])

print_name()

test.json

{
    "name" : "Rajkumar"
}

Now, if I just run => python app.py. I'm getting FileNotFoundError

1

There are 1 best solutions below

0
On BEST ANSWER

You need to add absolute path to the test.json.

app.py:

import json 
import os

def print_name():
    dir_path = os.path.dirname(__file__)

    with open(f"{dir_path}/test.json", mode='r') as json_file:
        py_dict = json.load(json_file)
    print(py_dict["name"])