簡體   English   中英

在 Python 中使用 JSON 元素加載相對路徑文件

[英]Using JSON Element for Relative Path File Load in Python

第一個軟件工作,我繼承了一個大量使用 JSON 的代碼庫。 我正在嘗試使用 Python 從訪問 JSON 元素中加載文本文件。 我的相對路徑理解有限,但我能夠在同一個子目錄中加載 python 模塊(雖然不使用 JSON)。 此數據文件位於同一文件夾中。

我在這里的 JSON 元素中解析和存儲數據:

with open(cfg) as fp:
    edict = json.load(fp)
if edict["dtype"] == "custom" :
    data = edict["dtype"]["custom"]["datapath"]

JSON文件的相關部分:

{
"dtype" : {
    "custom" : {
        "datapath" : "DataPipeLine/example_data.txt",
        "type" : "T",
        "X" : "encoder",
        "Y" : "encoder"
    }
  }
}

稍后在程序中將數據變量傳遞給函數時出現錯誤:

UnboundLocalError:在聲明之前嘗試將值分配給局部變量時,會引發分配錯誤之前引用的局部變量。

您的代碼中有太多錯誤

我假設你的項目目錄是這樣的

.
├── DataPipeLine
│   └── example_data.txt
├── cfg.json
└── main.py

有正確的代碼示例

import json
from pathlib import Path

# Get current directory
CUR_DIR = Path(__file__).parent.absolute()


def load_data(path: Path):
    print(path.read_text())


# cfg file path
cfg = CUR_DIR / 'cfg.json'
with cfg.open() as fp:
    edict = json.load(fp)

    # Check there is custom node or not
    if edict["dtype"]["custom"]:
        # Generate your datapath
        data_path = CUR_DIR / edict["dtype"]["custom"]["datapath"]
        load_data(data_path)

如果我的回答解決了您的問題,請接受它作為正確答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM