Python项目里用JSON做配置文件,具体怎么读取、修改和处理编码问题?
在Python中使用JSON作为参数配置文件有多种常见的应用场景和方法:
- **读取配置文件**:
- **直接读取**:对于配置文件路径固定的情况,可直接使用`open`函数打开JSON文件,再用`json.load`方法加载数据。例如读取路径为`D:\配置文件\arg.json`的文件:
```python
import json
jsondata = open(r'D:\配置文件\arg.json', 'r', encoding='utf-8')
load_data = json.load(jsondata)
inputPath = load_data['input_path']
shpPath = load_data['shp_path']
```
- **命令行指定路径**:当从命令行窗口调用工具时,可通过`sys.argv`获取配置文件的路径。示例代码如下:
```python
import sys
import json
jsondata = open(sys.argv[1], 'r', encoding='utf-8')
load_data = json.load(jsondata)
inputPath = load_data['input_path']
shpPath = load_data['shp_path']
```
利用此方法调用的命令示例为:`NDVI.exe D:\配置文件\arg.json` [^2]。
- **读取和更新配置的函数实现**:在`main.py`中可以定义函数来读取和更新配置。以下是示例代码:
```python
import json
def read_config():
"""读取配置"""
with open("config.json") as json_file:
config = json.load(json_file)
return config
def update_config(config):
"""更新配置"""
with open("config.json", 'w') as json_file:
json.dump(config, json_file, indent=4)
return None
```
- **字符集处理**:在读取JSON文件时,要确保字符集与文件一致。例如文件使用`GBK`字符集,代码如下:
```python
import json
with open('config.json', 'r', encoding='GBK') as config_j:
cfg = json.load(config_j)
print(cfg)
print(cfg.get('老师', '无效参数'))
print(cfg['学生'].get('N03', {'姓名': '未登记', '年龄': '未知'}))
```
- **变量使用**:当通过`config = read_config()`获得的配置`config`是一个字典时,不能直接将键值当作变量使用,通常需要每个变量执行一次类似`target_dir = config["target_dir"]`的操作 [^5]。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考