简体   繁体   English

如何修复json导入两个目录

[英]How to fix json imports two directories up

I am trying to import a config json file from a different directory from where i want to use it. 我正在尝试从我要使用的其他目录中导入配置json文件。 Am getting this error : 正在收到此错误:

with open('../../config/config.json', 'r') as f: IOError: [Errno 2] No such file or directory: '../../config/config.json' 使用open('../../ config / config.json','r')为f:IOError:[Errno 2]没有这样的文件或目录:'../../config/config.json'

This is what I did. 这就是我所做的。 I tried importing JSON library and load the file as shown in the code below. 我尝试导入JSON库并加载文件,如下面的代码所示。

import json

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

Any help will be appreciated 任何帮助将不胜感激

You need to insert complete path to import the file successfully. 您需要插入完整路径才能成功导入文件。

The issue is with your ../../config 问题出在您的../../config

Instead give the complete path of the file. 而是提供文件的完整路径。

What you're doing does work, however isn't great practice and is dependent on other variables for it to work. 您正在做的事情确实有效,但是这不是一个好习惯,它依赖于其他变量才能起作用。 I'd suggest putting the full (absolute) path of the file you want to read in: 我建议将要读取的文件的完整(绝对)路径放入:

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

Alternatively you can build the path using the sys module and assign it to a variable to be used in the open call, I'd suggest looking at the docs 或者,您可以使用sys模块构建路径,并将其分配给要在open调用中使用的变量,建议您查看文档

did you try whether that is the correct path? 您尝试过这是否是正确的路径吗? pathlib.Path can help you here pathlib.Path可以在这里帮助您

from pathlib import Path

parent = Path("Path("../../config/"
parent.exists(), parent.is_dir()

p = parent / "config.json"
p.exists()

You can use pandas to read Json format data. 您可以使用熊猫读取Json格式的数据。

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

Note Use path like: ././config/config.json and call os.chdir('..') before accessing file. 注意使用如下路径:././config/config.json并在访问文件之前调用os.chdir('..')。

For reference click here 供参考, 请点击这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM