首页 > 解决方案 > 没有这样的文件或目录: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
   

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

附件文件.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', encoding = 'utf-8', 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 文件的所有其他内容都给了我同样的错误。

如果有人可以帮助我,我将不胜感激。

提前谢谢了。

标签: pythonjsondirectorynao-robotchoregraphe

解决方案


通过写作:

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

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

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

在 Choregraphe Python 框中,您可以使用以下表达式找到安装行为的绝对路径:

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, encoding = 'utf-8', mode='r') as json_file:
    self.json_data = json.load(json_file)

推荐阅读