Search code examples
python-3.ximportmodulepackagefilenotfounderror

Python FileNotFoundError :


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


Solution

  • 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"])