2

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!

1
  • try this import os p = os.path.abspath('..') if you need the answer please comment Commented Sep 2, 2021 at 5:14

3 Answers 3

3

Another solution would be to use Pathlib.Path.

import json
from pathlib import Path


try:
    base = Path(__file__).parent.parent
    filename = base / 'json_files_folder' / 'one.json'
    with  open(filename) as file:
        data = json.load(file)
    print(data)
except:
     return "error"
Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

Besides the solution itself changing the exception handler was a good idea.
0

If you are on Windows, use shorter option:

import json
import os

try:
    path_to_file = os.path.join(os.pardir, "json_files_folder", "one.json")
    with  open(path_to_file) as file:
        data = json.load(file)
    print(data)
except:
    print("An error occured")

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.