Python资源文件管理

2024-04-25 05:43:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道用Python访问资源文件的好方法。现在我正在使用pkgutil.get_data(…),它在安装包之后就可以正常工作,但是在我的开发环境中就不行了,因为我有'src'和'resources'目录作为同级目录。我还将test\u资源保存在另一个同级目录中,希望测试能够找到test\u资源。有没有办法扩展pkgutil的搜索路径?我的文件结构示例如下:

├── resources
│   └── download
│       └── file
│           └── type
│               └── config.yaml
├── src
│   └── download
│       ├── __init__.py
│       ├── file
│       │   ├── __init__.py
│       │   ├── type
│       │   │   ├── __init__.py
│       │   │   └── code.py
├── test
│   ├── test_x.py
│   ├── test_y.py
│   └── test_z.py
└── test_resources
    ├── test_resources1.yaml
    └── test_resources2.yaml

Tags: 文件方法pytestsrc目录yamlget
1条回答
网友
1楼 · 发布于 2024-04-25 05:43:51

尝试将这些路径传递给pkgutil调用

ResrcConfigPath = os.path.expanduser('~path/to/resources/download/file/type/config.yaml')

TestResourcesDir = os.path.expanduser('~path/to/test_resources/')
testResource1Path = os.path.join(TestResourcesDir, "test_resources1.yaml")
testResource2Path = os.path.join(TestResourcesDir, "test_resources2.yaml")

相关问题 更多 >