jesus fernandez
jesus fernandez

Reputation: 369

How can I open a file within the above dir in python?

I am doing a script which opens a file(json) and then do something with it, I am having an issue as the interpreter cannot find the route and actually the route I get when I print it out on screen is quiet weird. I am working on windows if it helps. So this is a bit of code:

def playActions(filename):
    # Read the file
    script_dir = os.path.dirname(__file__)
    filepath = os.path.join(script_dir, 'recordings', filename)
    print(filepath)
    with open(filepath, 'r') as jsonfile:
        # parse the json
        data = json.load(jsonfile)

and this is this the output:

  File "C:/Users/anton/PycharmProjects/videogame_bot/playback.py", line 38, in playActions
    with open(filepath, 'r') as jsonfile:
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\anton\\PycharmProjects\\videogame_bot\\recordings\\actions_test_2020-07-29.json'
C:\Users\anton\PycharmProjects\videogame_bot
C:\Users\anton\PycharmProjects\videogame_bot\recordings\actions_test_2020-07-29.json

The thing is that when I print filepath, the result on screen looks fine, I do not know what I am missing though. The folder herarchy is as you can see

enter image description here

Upvotes: 0

Views: 82

Answers (1)

Mullo
Mullo

Reputation: 106

You need to get absolute path of file and then get directory. In your sample code you get relative path and file can not be found.

Try to modify you code like this

import os
import json

def playActions(filename):
    # Get absolute path of file
    full_path = os.path.abspath(__file__)
    # Extract directory from the path
    script_dir = os.path.dirname(full_path)
    filepath = os.path.join(script_dir, 'recordings', filename)
    print(filepath)
    with open(filepath, 'r') as jsonfile:
        # parse the json
        data = json.load(jsonfile)

It works for me, but unfortunately i have no Windows PC, i run this code on OS X.

Upvotes: 1

Related Questions