python配置文件使用介绍---configparser

目录

简介

python自带的configparser模块可以读、写、改配置文件

ini配置文件包含三部分,section、ItemName、value

注意:

  1. section对大小写敏感,而ItemName不区分大小写,在配置编写完写入配置文件后,item大写会变成小写
  2. section在配置文件中必须唯一,name在不同section中可以重复使用,value可以使用多行的值
  3. value如果存在空格,作为参数传给其他变量需要注意使用双引号,否则会按照空格拆分成多个值传入而出错
[Default]  # section
qc = fastp # qc is name, fastp is value
alignmethod = STAR
de = edgeR
[Group] 
sample = A1 A2 A3 A4 A5 A6
group = C1 C1 Day3 Day3 Day7 Day7
[Path]
scriptpath = /workspace/Script
[MethodList]
alignmethod = STAR hisat2 bwa
qc = fastp cutadapt
[AlignOrganPath]
homo_spamis = homo_sapiens/GRCh38
[indexName]
star = STAR_index
[group_compare]
group = C1 Day3 Day7
group1 = C1 Day3
[NMDS]
group = group

读取配置文件

import configparser
# 创建配置文件对象
con = configparser.ConfigParser()
# 读取文件
config.read('example.ini')
# 获取所有section
sections = con.sections()
# ['url', 'email']
# 获取特定section
items = con.items('url') # 返回结果为元组
# [('baidu','https://www.zalou.cn'),('port', '80')] # 数字也默认读取为字符串
# 可以通过dict方法转换为字典
items = dict(items)
# 读取值
value = con[section][itemName]
# 取出某个section全部itemName和value
items = dict(con.items('section'))
# 获取字典中所有的key
items=items.items()
#for循环遍历items
for item in items:
    key=item[0]
    value=item[1]
    print('%s\t%s'%(key,value)

写入配置

config = configparser.ConfigParser()
# method1
config['DEFAULT'] = {'ServerAliveInterval': '45',
                     'Compression': 'yes',
                     'CompressionLevel': '9'}
# method2
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
# method3
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Port'] = '50022'   
# 写入配置文件
with open('example.ini', 'w') as configfile:
    config.write(configfile)