gpt-4o-2024-08-06· OpenAI
WildChat-4.8M (AI2)
python代码,如何读取config文件中类似这样的数据,xxxx=yyyy
- User
python代码,如何读取config文件中类似这样的数据,xxxx=yyyy
- Assistant
在Python中读取类似于
key=value格式的配置文件数据,可以使用多种方法。以下是一些常用的方法:方法1: 使用
configparser模块configparser是标准库的一部分,专门用于处理配置文件。需要注意的是,configparser处理的配置文件一般有节(section)的概念。首先,将配置文件内容修改为:
[DEFAULT] xxxx=yyyy然后,使用
configparser读取:import configparser # 创建配置解析器对象 config = configparser.ConfigParser() # 读取配置文件 config.read('config.ini') # 访问数据 xxxx_value = config['DEFAULT']['xxxx'] print(f'xxxx = {xxxx_value}')方法2: 使用自定义解析
如果你的文件格式只是简单的
key=value而没有节,也可以使用文件操作和字符串方法来自定义解析:# 定义读取配置文件的函数 def read_config(filename): config_dict = {} # 打开配置文件 with open(filename, 'r') as file: for line in file: # 去除开头和结尾的空格字符 line = line.strip() # 忽略空行和注释行 if not line or line.startswith('#'): continue # 分割为 key 与 value key, value = line.split('=', 1) config_dict[key.strip()] = value.strip() return config_dict # 使用函数读取 config = read_config('config.txt') xxxx_value = config.get('xxxx', None) # 默认值为 None print(f'xxxx = {xxxx_value}')