简体   繁体   中英

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

在此处输入图像描述

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM