Python json file reading from subdirectory breaking

  json, pycharm, python

My python code is throwing up an error when I try to run this code:

def get_recipe(itemname):
    recipe_ids = ["A1", "A2", "A3", "B1", "B2", "B3", "C1", "C2", "C3"]
    current_item_recipe = []
    item_path = "./neu-repo/items/{}".format(itemname)
    print(item_path, itemname)
    current_item = open(item_path, "r", encoding="utf-8")
    current_item = json.loads(current_item.read())
    for i in range(9):
        current_item_recipe.append(current_item["recipe"][f"{recipe_ids[i]}"])

    return current_item_recipe

Specifically, this output:

./neu-repo/items/TERMINATOR.json
./neu-repo/items/.json
Traceback (most recent call last):
  File "C:UserstomdaPycharmProjectsfireTechPythonProjectsFlaskmain.py", line 292, in <module>
    print(get_craft_cost("TERMINATOR", nestcount))
  File "C:UserstomdaPycharmProjectsfireTechPythonProjectsFlaskmain.py", line 219, in get_craft_cost
    if get_recipe(item_file) != "":
  File "C:UserstomdaPycharmProjectsfireTechPythonProjectsFlaskmain.py", line 172, in get_recipe
    current_item = open(item_path, "r", encoding="utf-8")
FileNotFoundError: [Errno 2] No such file or directory: './neu-repo/items/.json'

I am very confused. Firstly, I only have 1 print statement (to check on the variable. The debugger says it’s all as it should be) so I have no idea where the second printout of the path is coming from. As far as I can tell, the path seems to be overwritten inbetween the lines, removing only the itemname, which is ".json" is appended to in a different subroutine: def get_craft_cost(itemname, nestings): item_file = itemname + ".json" recipe = get_recipe(item_file)
(there’s more but that’s what’s relevant).

So what is going on? Is my code cursed as I thought?

(full code if needed: https://github.com/QuintBrit/flask-website/tree/master)

Source: Python Questions

LEAVE A COMMENT