Sword Slash
Sword Slash

Reputation: 17

How can I open a json file from another folder?

I am trying to make a code in python that imports a JSON file from a folder into my program in order for it to access the data inside. However, I am facing errors

    global bees
    with open('data/bees.json') as f:
        bees = json.load(f)["bees"]

Where in the data/bees.json I have this:

    {
    "bees": []
    }

The error I get

Traceback (most recent call last):
  File "d:/Entertainment/Coding/Python/Pygame/BUG WORLD/main.py", line 70, in <module>
    bees = json.load(f)
  File "C:\Users\ernes\AppData\Local\Programs\Python\Python37-32\lib\json\__init__.py", line 296, in load
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
  File "C:\Users\ernes\AppData\Local\Programs\Python\Python37-32\lib\json\__init__.py", line 348, in loads
    return _default_decoder.decode(s)
  File "C:\Users\ernes\AppData\Local\Programs\Python\Python37-32\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\ernes\AppData\Local\Programs\Python\Python37-32\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Is there a way I am able to import JSON files from another folder without causing any errors?? Please help

Upvotes: 0

Views: 1922

Answers (3)

zvi
zvi

Reputation: 4696

Looks like you're on Windows, so:

with open(r'c:\path\to\file\bees.json') as json_file:
    bees_js = json.load(json_file)

Upvotes: 2

DeepNet
DeepNet

Reputation: 161

You might want to try the following:

import json

with open('path_to_file/bees.json') as json_file:
    bees_js = json.load(json_file)

Upvotes: 0

id1
id1

Reputation: 221

The relative path should be open("data/bees.json") without the /, starting a path with / means absolute path from the root.

Upvotes: 0

Related Questions