hutool.core.io.resource¶
资源工具模块
Module Contents¶
Classes¶
资源工具类 |
|
异步资源工具类,提供资源读取的异步方法。 |
API¶
- class hutool.core.io.resource.ResourceUtil¶
资源工具类
- _resource_paths: List[str] = []¶
- classmethod add_resource_path(path: str) None¶
添加资源搜索路径
- 参数:
path – 资源目录的绝对或相对路径
- static get_resource(path: str) str¶
获取资源的绝对路径
按以下顺序查找资源: 1. 绝对路径直接返回 2. 当前工作目录 3. 已注册的资源搜索路径
- 参数:
path – 资源的相对或绝对路径
- 返回:
资源的绝对路径
- 抛出:
FileNotFoundError – 资源不存在时抛出
- static get_resource_bytes(path: str) bytes¶
读取资源为字节数组
- 参数:
path – 资源的相对或绝对路径
- 返回:
资源内容的字节数组
- 抛出:
FileNotFoundError – 资源不存在时抛出
- static get_resource_str(path: str, charset: str = 'utf-8') str¶
读取资源为字符串
- 参数:
path – 资源的相对或绝对路径
charset – 字符编码,默认 utf-8
- 返回:
资源内容的字符串
- 抛出:
FileNotFoundError – 资源不存在时抛出
- static get_resource_stream(path: str) IO¶
获取资源的文件流
调用方负责关闭返回的文件流。
- 参数:
path – 资源的相对或绝对路径
- 返回:
可读的文件对象
- 抛出:
FileNotFoundError – 资源不存在时抛出
- static get_resources(pattern: str) List[str]¶
根据模式匹配获取资源列表
支持通配符模式(如 “.txt”、”data/.csv”)。 在当前工作目录和已注册的资源搜索路径中搜索。
- 参数:
pattern – 文件名匹配模式(支持 * 和 ? 通配符)
- 返回:
匹配的资源绝对路径列表
- static _search_in_dir(base_dir: str, pattern: str, results: List[str]) None¶
在指定目录中递归搜索匹配的文件
- 参数:
base_dir – 基础搜索目录
results – 结果列表(原地修改)
- Pattern:
文件名匹配模式
- class hutool.core.io.resource.AsyncResourceUtil¶
异步资源工具类,提供资源读取的异步方法。
与
ResourceUtil方法名一致,读取方法均为协程,需用await调用。 底层使用aiofiles做非阻塞文件读取。备注
需要安装可选依赖
aiofiles``(``pip install 'hutool-python[async]')。 未安装时调用异步方法会抛出清晰的ImportError。示例:
from hutool import AsyncResourceUtil data = await AsyncResourceUtil.get_resource_bytes("config/app.json")
- static _check_aiofiles() None¶
检查 aiofiles 是否已安装,未安装时抛出清晰的 ImportError。
- async static get_resource_bytes(path: str) bytes¶
异步读取资源为字节数组。
- 参数:
path – 资源的相对或绝对路径
- 返回:
资源内容的字节数组
- 抛出:
FileNotFoundError – 资源不存在时抛出
ImportError – 未安装 aiofiles 时抛出
- async static get_resource_str(path: str, charset: str = 'utf-8') str¶
异步读取资源为字符串。
- 参数:
path – 资源的相对或绝对路径
charset – 字符编码,默认 utf-8
- 返回:
资源内容的字符串
- 抛出:
FileNotFoundError – 资源不存在时抛出
ImportError – 未安装 aiofiles 时抛出
- async static get_resource_stream(path: str)¶
异步获取资源的文件流(
aiofiles异步上下文管理器)。调用方需用
async with打开并负责关闭,例如:async with await AsyncResourceUtil.get_resource_stream("a.txt") as f: data = await f.read()
- 参数:
path – 资源的相对或绝对路径
- 返回:
可读的异步文件对象
- 抛出:
FileNotFoundError – 资源不存在时抛出
ImportError – 未安装 aiofiles 时抛出
- async static add_resource_path(path: str) None¶
添加资源搜索路径。
委托同步实现,保证与
ResourceUtil共享同一份资源搜索路径, 从而get_resource*系列方法能找到通过本类注册的路径。
- async static get_resource(path: str) str¶
异步获取资源的绝对路径。
- async static get_resources(pattern: str) List[str]¶
异步根据模式匹配获取资源列表。