【问题标题】:How to fix json imports two directories up如何修复json导入两个目录
【发布时间】:2019-08-30 09:23:57
【问题描述】:

我正在尝试从我想要使用它的不同目录导入配置 json 文件。收到此错误:

用 open('../../config/config.json', 'r') as f: IOError:[Errno 2] 没有这样的文件或目录:'../../config/config.json'

这就是我所做的。我尝试导入 JSON 库并加载文件,如下面的代码所示。

import json

with open('../../config/config.json', 'r') as f:
config = json.load(f)

任何帮助将不胜感激

【问题讨论】:

  • 给出绝对路径而不是相对路径

标签: python


【解决方案1】:

您需要插入完整路径才能成功导入文件。

问题在于您的 ../../config

而是给出文件的完整路径。

【讨论】:

    【解决方案2】:

    您是否尝试过这是否是正确的路径? pathlib.Path可以帮到你

    from pathlib import Path
    
    parent = Path("Path("../../config/"
    parent.exists(), parent.is_dir()
    
    p = parent / "config.json"
    p.exists()
    

    【讨论】:

      【解决方案3】:

      你正在做的事情确实有效,但这不是很好的做法,它需要依赖其他变量才能发挥作用。我建议将您要读取的文件的完整(绝对)路径放入:

      with open('the/full/path/to/config/config.json', 'r') as f:
      config = json.load(f)
      

      或者,您可以使用sys 模块构建路径并将其分配给要在open 调用中使用的变量,我建议查看docs

      【讨论】:

        【解决方案4】:

        可以使用pandas读取Json格式数据。

        import pandas as pd
        pd.read_json('<PATH>')
        

        注意使用如下路径:././config/config.json 并在访问文件之前调用 os.chdir('..')。

        供参考click here

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-12-05
          • 2019-05-30
          • 1970-01-01
          • 2014-05-22
          相关资源
          最近更新 更多