2020年6月3日 / 91次阅读 / Last Modified 2020年6月3日
configparser模块
记录两个自己写的基于configparser模块读写配置项的函数,简单通用。写配置项的函数同时兼顾了创建配置文件的作用。
import os
import configparser
CONFIG_FILE = 'config.ini'
def readConfig(section, name):
"""Read a config value by section and name."""
try:
config = configparser.ConfigParser()
config.read(CONFIG_FILE)
rv = config[section][name]
except:
return None
else:
return rv
def writeConfig(section, name, value):
"""Add or update an configurable item in config file.
Create config file if it is not existed."""
config = configparser.ConfigParser()
config.read(CONFIG_FILE) # no raise if file isn't existed.
if section not in config:
config[section] = {}
config[section][name] = value
with open('_'+CONFIG_FILE, 'w') as f:
config.write(f)
try:
os.remove(CONFIG_FILE)
except:
pass
os.rename('_'+CONFIG_FILE, CONFIG_FILE)
-- EOF --
本文链接:https://www.pynote.net/archives/2033
©Copyright 麦新杰 Since 2019 Python笔记