【问题标题】:No such file or directory: 'file.json' Error in Choregraphe 2.8没有这样的文件或目录:Choregraphe 2.8 中的“file.json”错误
【发布时间】:2021-03-06 14:53:33
【问题描述】:

我正在尝试访问 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', 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 文件的所有其他方法都给了我同样的错误。

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

非常感谢。

【问题讨论】:

  • 错误可能在read_json.py,但你没有分享代码。

标签: python json directory nao-robot choregraphe


【解决方案1】:

通过写作:

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

【讨论】:

    猜你喜欢
    • 2021-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-08
    • 2013-11-04
    相关资源
    最近更新 更多