简体   繁体   English

使用pkg_resources在python包的当前发行版中加载JSON文件

[英]Load JSON file in current distribution of a python package using pkg_resources

I am building a package that has the following directory structure - 我正在构建一个具有以下目录结构的软件包-

terraai_preprocessing
|setup.py
||MANIFEST.in
|terraai_preprocessing
  |__init__.py
  |combinatorics
  |preprocessing
    |__init__.py
    |config.json
    |pp_main.py
    |pp_helpers.py

I am trying to load config.json into pp_helpers.py using pkg_resources, as mentioned on other similar questions. 我正在尝试使用pkg_resources将config.json加载到pp_helpers.py中,如其他类似问题所述。 I am sure the file exists because - 我确定该文件存在,因为-

>>print resource_exists('terraai_preprocessing.preprocessing', 'config.json')
>>True

I have tried using the following but ended up with errors, - 我尝试使用以下内容,但最终出现错误,-

>>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

What am I doing wrong 我究竟做错了什么

It has to be like: 它必须像:

with open('data.json', encoding='utf-8') as data_file:
    data = json.loads(data_file.read())

so in your case 所以你的情况

 config = json.loads(f.read())

Python could not find the file as the function resource_filename() returns the address with \\\\ as separators. Python无法找到该文件,因为函数resource_filename()返回以\\\\作为分隔符的地址。 By replacing \\\\ with / it was able to locate the file. 通过将\\\\替换为/ ,便可以找到文件。

So I used the following code - 所以我用下面的代码-

>> file_location = resource_filename('terraai_preprocessing.preprocessing','config.json').replace('\\',"/")

>> with open(file_location,'r') as f:
      config = json.load(f)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM