pythonpython-3.xoperating-systembackendfilepath

How to get path of a file in another folder using os python


Let's say this is my folder structure,

project
    main_folder
         file.py
    json_files_folder
         one.json
         two.json
         three.json

When I run the file.py file it should fetch the path of the files in json_files_folder and open a file, Here is my code,

import json
import os


try:
    file_path = os.path.dirname(os.path.realpath(__file__))
    filename = file_path + '/' + 'one' + '.json'
    with  open(filename) as file:
        data = json.load(file)
    return data
except:
     return "error"

what should I change in file_path variable to make this code work? Thanks in advance!


Solution

  • Your json files are present in json_files_folder hence you need to traverse to that path to get the json files. Here is the code for the same:

    import json
    import os
    
    
    try:
        file_path = os.path.dirname(os.path.realpath(__file__))
        filename = file_path + '/../json_files_folder/one.json'
        with  open(filename) as file:
            data = json.load(file)
        print (data)
    except Exception as ex:
         raise ex