Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中打开上述目录中的文件?_Python_Python 3.x_Windows - Fatal编程技术网

如何在python中打开上述目录中的文件?

如何在python中打开上述目录中的文件?,python,python-3.x,windows,Python,Python 3.x,Windows,我正在做一个脚本,打开一个文件(json),然后用它做一些事情,我遇到了一个问题,因为解释器找不到路径,实际上我在屏幕上打印出来时得到的路径非常奇怪。我正在windows上工作,如果它有帮助的话。这是一段代码: def playActions(filename): # Read the file script_dir = os.path.dirname(__file__) filepath = os.path.join(script_dir, 'recordings',

我正在做一个脚本,打开一个文件(json),然后用它做一些事情,我遇到了一个问题,因为解释器找不到路径,实际上我在屏幕上打印出来时得到的路径非常奇怪。我正在windows上工作,如果它有帮助的话。这是一段代码:

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)
这就是输出:

  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
问题是,当我打印文件路径时,屏幕上的结果看起来很好,但我不知道我遗漏了什么。文件夹herarchy如您所见


您需要获取文件的绝对路径,然后获取目录。在示例代码中,您得到了相对路径,但找不到文件

尝试这样修改代码

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)

它适合我,但不幸的是我没有Windows PC,我在OS X上运行此代码。

您能将
script\u dir
更改为
OS.path.abspath(OS.path.dirname(\u file\u))
?这给了你什么?我试过了,我得到了这个:``用open(filepath,'r')作为jsonfile:FileNotFoundError:[Errno 2]没有这样的文件或目录:“C:\\Users\\anton\\PycharmProjects\\videogame\u bot\\recordings\\actions\u test\u 2020-07-29.json”````我真的无法找出错误……你能试着运行(Win+R)->记事本吗“C:\Users\anton\PycharmProjects\videogame\u bot\recordings\actions\u test\u 2020-07-29.json”字符可能与您想象的稍有不同。您可以打开外壳并
glob.glob('C:\\Users\\anton\\PycharmProjects\\videogame\u bot\\recordings\\\*.json')
,然后将返回的名称与“actions\u test\u 2020-07-29.json”进行比较“。也许您的unicode下划线或破折号与您预期的不同。我得到的是相同的。。。刚才还在工作,哈哈哈,我不知道我做了什么。但我在你的截图中注意到一点奇怪的事情,可能是你在测试和2020-07-29之间有空格?天哪,你是对的,就是这样,我应该打错的。非常感谢<代码>文件通常是绝对的,从错误消息判断,在这种情况下是绝对的。