没有这样的文件或目录:Choregraphe 2.8 中的“file.json”错误

问题描述

我正在尝试访问 choregraphe 2.8 中的 json 文件,但它无法识别它的位置。我正在使用 NAO6 虚拟机器人并将外部 python 脚本导入到这个平台,除了读取和打开 json 文件外,它工作正常。

我在导入的 python 脚本中包含了这部分:

read_json.py

class JsonData():
    def open_json(self):
      with open('file.json',encoding = 'utf-8',mode='r') as json_file:
        self.json_data = json.load(json_file)
      return self.json_data

   def get_param(self,parameter):
     # open json file to access data
     self.open_json()
     
     # get the key values from json file
     if parameter == "test":
       name = self.json_data["Name"]
         return name
   

我用这个 video 来指导我导入外部 python 脚本:

attachment_file.py

    #other parts of the code are not included...
    def onLoad(self):
        self.framemanager = ALProxy("ALFrameManager")

    def onInput_onStart(self):
        self.folderName = self.framemanager.getBehaviorPath(self.behaviorId) + self.getParameter("File name")

        if (self.folderName) not in sys.path:
            sys.path.insert(0,self.folderName)
        self.onStopped()

    def onUnload(self):
        if (self.folderName) in sys.path:
            sys.path.remove(self.folderName)

我有一个使用 choregraphe 工具编写在框中的 Python 脚本。当我尝试导入 read_json.py 以读取 json 文件时,出现此错误

...\choregraphe\...\data\PackageManager\apps\.lastUploadedchoregrapheBehavior\behavior_1/..\read_json.py",line 9,in open_json with open('file.json',mode='r') as json_file: IOError: [Errno 2] No such file or directory: 'file.json'  

对于我用来导入 read_json.py 的文件的 onInput_onStart(self) 部分是这样写的:

 def onInput_onStart(self):
        import read_json        
        self.a = read_json.JsonData()
        json_data = self.a.show_param("test")   #string output
        self.tts.say(json_data)

我已经搜索了很多关于如何从 choregraphe 2.8 导入其他文件方法,但是我尝试访问 json 文件的所有其他方法,除了上述方法,都给了我同样的错误

如果有人能帮我解决这个问题,我将不胜感激。

非常感谢。

解决方法

通过写作:

open('file.json',encoding = 'utf-8',mode='r')

您依靠 Python 解释器的当前工作目录来查找 file.json

一般在 Python 中,建议您使用绝对路径以避免此类混淆,并确保您控制要尝试读取的文件。

在 Choregraphe Python 框中,您可以使用以下表达式找到 the absolute path to your installed behavior

self.behaviorAbsolutePath()

假设您的 file.json 位于您应用的 behavior_1 目录下,您可以通过以下方式获取其绝对路径:

os.path.join(self.behaviorAbsolutePath(),'file.json')

适用于您的情况,这就是您可以正确读取文件的方式:

json_file_path = os.path.join(self.behaviorAbsolutePath(),'file.json')
with open(json_file_path,mode='r') as json_file:
    self.json_data = json.load(json_file)