json 格式的配置文件读写
import json
def read_config_json():
"""读取JSON格式的配置文件"""
script_dir = os.path.dirname(__file__)
file_path = os.path.join(script_dir, 'config.json')
try:
with open(file_path, 'r', encoding='utf-8') as file:
config_data = json.load(file)
return config_data
except FileNotFoundError:
print(f"配置文件 {file_path} 未找到。将创建一个新的配置文件。")
except json.JSONDecodeError:
print(f"配置文件 {file_path} 不是有效的JSON格式。将创建一个新的配置文件。")
except Exception as e:
print(f"读取配置文件时发生错误:{e}")
return None
def write_config_json(config_data):
"""写入JSON格式的配置文件"""
script_dir = os.path.dirname(__file__)
file_path = os.path.join(script_dir, 'config.json')
try:
with open(file_path, 'w', encoding='utf-8') as file:
json.dump(config_data, file, ensure_ascii=False, indent=4)
print(f"配置文件 {file_path} 写入成功。")
except Exception as e:
print(f"写入配置文件时发生错误:{e}")
if __name__ == "__main__":
config = read_config_json()
if config is None:
config = {}
config['example_section'] = {}
config['example_section']['example_option'] = 'default value'
print("新创建的配置信息:", config)
else:
print("读取到的配置信息:", config)
config['example_section'] = 'new value'
write_config_json( config)
ini格式的配置文件读写
import os
import configparser
def write_config(section, option, value):
'''
向 ini 配置文件中写入配置信息
:param config_path: 配置文件路径
:param section: 配置项所在的 section 名称
:param option: 配置项名称
:param value: 配置项的值
'''
script_dir = os.path.dirname(__file__)
config_path = os.path.join(script_dir, 'config.ini')
config = configparser.ConfigParser()
config.read(config_path)
if not config.has_section(section):
config.add_section(section)
config.set(section, option, value)
with open(config_path, 'w' ,encoding='utf-8-sig') as f:
config.write(f)
def read_config():
'''
读取 ini 配置文件的内容
:param config_path: 配置文件的路径
'''
script_dir = os.path.dirname(__file__)
config_path = os.path.join(script_dir, 'config.ini')
config = configparser.ConfigParser()
try:
with open(config_path, 'r', encoding='utf-8-sig') as f:
config.read_file(f)
except FileNotFoundError:
print("Config file not found.")
return
except configparser.Error as e:
print("Failed to read config file:", e)
return
sections = config.sections()
for section in sections:
options = config.options(section)
for option in options:
value = config.get(section, option)
print(f"Section: {section}, Option: {option}, Value: {value}")