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

如何让Python的readFileBytes函数支持读取相对路径文件?

解决文件路径找不到的简便方法

最直接的解决方案是基于脚本文件所在目录构造目标文件的绝对路径,避免当前工作目录带来的路径解析问题。

方法1:修改调用代码(无需改动原函数)

在调用读取函数前,先通过__file__获取脚本所在目录,再拼接目标文件的相对路径:

from pathlib import Path
# 获取当前脚本所在的目录
script_dir = Path(__file__).parent
# 拼接目标文件的相对路径(根据实际文件层级调整)
target_path = script_dir / "villages" / "common" / "iron.nbt"
nbt = readFileBytes(target_path)

方法2:优化读取函数(自动适配脚本目录)

如果希望函数自动处理相对路径,可修改readFileBytes,让相对路径默认基于脚本所在目录解析,同时优化文件句柄的管理:

from pathlib import Path
from typing import Union

def readFileBytes(
    filePath: Union[Path, str]
) -> bytes:
    script_dir = Path(__file__).parent
    file_path = Path(filePath)
    # 若为相对路径,基于脚本目录转换为绝对路径
    if not file_path.is_absolute():
        file_path = script_dir / file_path
    # 使用with语句自动管理文件,避免手动close的疏漏
    with open(file_path, 'rb') as file_obj:
        raw_bytes = file_obj.read()
    print("Path: ", file_path)
    return raw_bytes

额外检查项

你提供的调用代码里存在拼写错误:./villages/commom/animals/cat_black.nbt中的commom应为common,这类拼写问题也会导致文件找不到。

内容的提问来源于stack exchange,提问作者Jee Bluetru

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 23:07:13