【问题标题】:I want to open a json file in python but got an error. It said No such file or directory我想在 python 中打开一个 json 文件,但出现错误。它说没有这样的文件或目录
【发布时间】:2021-08-05 10:49:50
【问题描述】:

enter image description here

我这样写代码:

intents = json.loads(open('intents.json').read())

【问题讨论】:

  • 您确定文件intents.json 与您正在运行的脚本位于同一目录中吗?导演:D:\L.I.S.A\
  • 当前工作目录中不存在该文件。您的工作目录可能不是您所期望的。
  • 使用import os;os.getcwd()

标签: python json python-3.x file-not-found


【解决方案1】:

检查您的intents.json 文件是否在您的python 文件所在的同一文件夹中。

【讨论】:

    【解决方案2】:

    例如,您可以使用os 内置模块来检查文件是否存在,并使用os.path 进行路径操作。查看官方文档https://docs.python.org/3/library/os.path.html

    import os
    
    file = 'intents.json'
    # location of the current directory
    w_dir = os.path.abspath('.'))
    if os.path.isfile(os.path.join(w_dir, file)):
        with open(file, 'r') as fd:
           fd.read()
    else:
        print('Such file does not exist here "{}"...'.format(w_dir))
    

    【讨论】:

      【解决方案3】:

      你可以使用pathlib:

      import pathlib
          
         
      
      filepath = pathlib.Path('intents.json')
      if filepath.exists():
          intents = json.loads(open('intents.json').read())
      else:
          print(f"File {filepath} does not exit ")
      

      【讨论】:

        【解决方案4】:

        您可以尝试使用正常的文件操作打开文件,然后根据需要使用 json.load 或 json.loads 解析数据。据我所知,我可能不熟悉这种语法,您的语法是错误的。

        你可以这样打开文件:

        f = open(file_name)
        

        然后解析数据:

        data = json.load(f)
        

        您可以参考此链接了解更多信息和参考

        https://www.geeksforgeeks.org/read-json-file-using-python/

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-10-29
          • 1970-01-01
          • 2010-12-18
          • 1970-01-01
          • 2013-12-29
          • 2012-02-27
          • 2022-08-13
          相关资源
          最近更新 更多