使用 pkg_resources 在 python 包的当前分发中加载 JSON 文件
Load JSON file in current distribution of a python package using pkg_resources
我正在构建一个具有以下目录结构的包 -
terraai_preprocessing
|setup.py
||MANIFEST.in
|terraai_preprocessing
|__init__.py
|combinatorics
|preprocessing
|__init__.py
|config.json
|pp_main.py
|pp_helpers.py
我正在尝试使用 pkg_resources 将 config.json 加载到 pp_helpers.py 中,如其他类似问题所述。我确定该文件存在,因为 -
>>print resource_exists('terraai_preprocessing.preprocessing', 'config.json')
>>True
我尝试使用以下方法但最终出现错误,-
>>with open(resource_filename('terraai_preprocessing.preprocessing', 'config.json'),'r') as f:
config = json.load(f)
ValueError: No JSON object could be decoded
>>config = json.loads(resource_filename('terraai_preprocessing.preprocessing', 'config.json'))
ValueError: No JSON object could be decoded
>>config = json.loads(resource_stream('terraai_preprocessing.preprocessing', 'config.json'))
enter code here
>>config = json.loads(resource_string('terraai_preprocessing.preprocessing', 'config.json'))
ValueError: No JSON object could be decoded
我做错了什么
它必须像:
with open('data.json', encoding='utf-8') as data_file:
data = json.loads(data_file.read())
所以在你的情况下
config = json.loads(f.read())
Python 找不到文件作为函数 resource_filename()
returns 地址以 \
作为分隔符。通过用 /
替换 \
它能够找到文件。
所以我使用了以下代码 -
>> file_location = resource_filename('terraai_preprocessing.preprocessing','config.json').replace('\',"/")
>> with open(file_location,'r') as f:
config = json.load(f)
我正在构建一个具有以下目录结构的包 -
terraai_preprocessing
|setup.py
||MANIFEST.in
|terraai_preprocessing
|__init__.py
|combinatorics
|preprocessing
|__init__.py
|config.json
|pp_main.py
|pp_helpers.py
我正在尝试使用 pkg_resources 将 config.json 加载到 pp_helpers.py 中,如其他类似问题所述。我确定该文件存在,因为 -
>>print resource_exists('terraai_preprocessing.preprocessing', 'config.json')
>>True
我尝试使用以下方法但最终出现错误,-
>>with open(resource_filename('terraai_preprocessing.preprocessing', 'config.json'),'r') as f:
config = json.load(f)
ValueError: No JSON object could be decoded
>>config = json.loads(resource_filename('terraai_preprocessing.preprocessing', 'config.json'))
ValueError: No JSON object could be decoded
>>config = json.loads(resource_stream('terraai_preprocessing.preprocessing', 'config.json'))
enter code here
>>config = json.loads(resource_string('terraai_preprocessing.preprocessing', 'config.json'))
ValueError: No JSON object could be decoded
我做错了什么
它必须像:
with open('data.json', encoding='utf-8') as data_file:
data = json.loads(data_file.read())
所以在你的情况下
config = json.loads(f.read())
Python 找不到文件作为函数 resource_filename()
returns 地址以 \
作为分隔符。通过用 /
替换 \
它能够找到文件。
所以我使用了以下代码 -
>> file_location = resource_filename('terraai_preprocessing.preprocessing','config.json').replace('\',"/")
>> with open(file_location,'r') as f:
config = json.load(f)