You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python开发包中相对路径读取JSON文件失败的解决方法

解决Python包内JSON文件路径读取问题

你的判断完全正确:问题出在相对路径是基于当前执行代码的工作目录,而非包所在的目录。要实现包内资源的稳定读取,核心是基于包文件的绝对路径来构造JSON文件的路径,不受外部执行目录影响。

解决方案:利用__file__锚定包目录

__file__是Python模块的内置变量,会返回当前.py文件的绝对路径。通过它可以定位到包的目录,再拼接JSON文件的相对路径,就能得到稳定的绝对路径。

方法1:使用现代的pathlib库(推荐)

import json
from pathlib import Path
from typing import Tuple, List
from web3 import Web3
# 假设BaseRouter和Wallet是你已定义的类

def get_contract_details(relative_path: str) -> Tuple[str, List[str]]:
    # 获取当前模块所在目录的绝对路径
    module_dir = Path(__file__).parent
    # 拼接JSON文件的绝对路径(自动适配不同操作系统的路径分隔符)
    file_path = module_dir / relative_path
    with open(file_path, 'r') as file:
        content = json.load(file)
        return content['address'], content['abi']


DETAILS = {
    'uniswap': get_contract_details('_contracts/uniswap_v2_router.json')
}


class Uniswap(BaseRouter):
    def __init__(self, provider: Web3, wallet: Wallet):
        address, abi = DETAILS['uniswap']
        super().__init__(provider, wallet, address, abi)

方法2:使用传统的os.path模块

import json
import os
from typing import Tuple, List
from web3 import Web3

def get_contract_details(relative_path: str) -> Tuple[str, List[str]]:
    # 获取当前模块的绝对路径,再提取所在目录
    module_dir = os.path.dirname(os.path.abspath(__file__))
    # 拼接得到JSON文件的绝对路径
    file_path = os.path.join(module_dir, relative_path)
    with open(file_path, 'r') as file:
        content = json.load(file)
        return content['address'], content['abi']


DETAILS = {
    'uniswap': get_contract_details('_contracts/uniswap_v2_router.json')
}


class Uniswap(BaseRouter):
    def __init__(self, provider: Web3, wallet: Wallet):
        address, abi = DETAILS['uniswap']
        super().__init__(provider, wallet, address, abi)

包结构说明

确保你的包目录结构和路径对应,示例结构如下:

your_package/
├── __init__.py
├── router_module.py  # 存放上述代码的文件
└── _contracts/
    └── uniswap_v2_router.json

这样不管用户从哪个目录导入Uniswap类,代码都会基于包的实际位置找到JSON文件,不会再出现路径错误。

内容的提问来源于stack exchange,提问作者blnk.off

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 04:22:48