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

如何用Python importlib.resources读取同模块下的资源文件?

问题描述

目录结构

.
├── data
│   ├── __init__.py
│   └── fish.csv
└── fish_service.py

需求

希望在fish_service.py中通过from .data import all_fish的方式,获取csv文件中的鱼类列表(all_fish为csv内容组成的列表)。

当前实现(存在痛点)

已在data/__init__.py中用importlib.resources实现读取逻辑,但需要从父目录导入data,PyCharm提示不友好,代码如下:

import csv
from importlib.resources import files

from .. import data

all_fish = []
with files(data).joinpath("fish.csv").open() as file:
    reader = csv.DictReader(file)
    for fish in item_reader:
        all_fish.append(fish)

疑问

有没有更优的同模块内读取资源的方法?


优化方案

直接借助当前模块的__name__定位资源,无需跨层级导入data,调整后的data/__init__.py代码如下:

import csv
from importlib.resources import files

all_fish = []
# 利用当前模块标识获取资源路径
with files(__name__).joinpath("fish.csv").open() as file:
    reader = csv.DictReader(file)
    # 修正原代码笔误:item_reader改为reader
    for fish in reader:
        all_fish.append(fish)

说明

  • files(__name__)会直接指向当前data模块的所在路径,天然能找到同目录下的fish.csv,彻底消除跨层级导入的写法,PyCharm也不会再出现提示问题。
  • 顺带修复了原代码的笔误:循环变量item_reader应为reader,原代码运行时会抛出未定义的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 00:44:57