l# 1. JSON
加载config.json文件为无序字典
base_path = sys.path[0]
config_path = os.path.join(base_path, 'devices/config/')
def get_ip(type_key):
with open(config_path + 'config.json') as f:
config = json.load(f)
config_ip = config[type_key]['ip']
config_port = config[type_key]['port']
return config_ip, config_port
加载template.json为有序字典
base_path = sys.path[0]
config_path = os.path.join(base_path, 'devices/config/')
def get_template(file_name):
with open(config_path + file_name) as f:
template = json.load(f, object_pairs_hook=OrderedDict)
return template
# 转成有序的str
config_str = json.dumps(OrderedDict(template))
2. ini
加载global.ini文件为无序字典
base_path = sys.path[0]
globalPath = os.path.join(base_path, 'etc/')
globalConfig = globalPath + '/global.ini'
def load_global_config():
config_global = {}
cf = ConfigParser.ConfigParser()
cf.read(globalConfig)
config_global['MariaDB'] = {'host_ip': str(cf.get("MariaDB", "host_ip")),
'port': str(cf.get("MariaDB", "port"))}
return config_global
3. XML
转换xml文件为Element类
import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml') #载入数据
root = tree.getroot() #获取根节点
#从字符串读取数据
root = ET.fromstring(country_data_as_string)