ini配置文件,常备用作存储程序中的一些常用参数,文件可读,通过它程序可以变得更加灵活。

  python中自带配置文件ini相关模块configparser。

import configparser

#-------------ini配置文件的配置过程------------
# 打开配置文件,文件不存在时新建
con = configparser.ConfigParser()

# 读取文件内容,放进内存
con.read('first_ini.ini',encoding='utf-8')

# 添加一个section,并向section中添加参数。
# ini文件中,不能存在相同的section
try:
    con.add_section('open_vpn')
    con.set('open_vpn','user_name','xfchen')
    con.set('open_vpn','keywords','chen8422')
except configparser.DuplicateSectionError:
    print("section 'open_vpn' already exists.")

try:
    con.add_section('blogs')
    con.set('blogs','user_name','HelloPython2017')
    con.set('blogs','keywords','liushui816@')
except configparser.DuplicateSectionError:
    print("section blogs already exists.")

# 将内容写入文件
con.write(open('first_ini.ini','w'))

#----------------ini配置文件内容读取-------------

# # 找节点,返回全部节点名列表
section_namelist = con.sections()
print(section_namelist)   # ['open_vpn', 'blogs']

# 找节点下内容,返回全部指定节点下的keys
section_keys = con.options('open_vpn')
print(section_keys)    # ['user_name', 'keywords']

# 找指定节点下、指定key的值
#  get返回str,还可以使用getint、getfloat等
userName = con.get('open_vpn','user_name')
print(userName)    # xfchen

#----------------ini配置文件的修改-----------------

# 检查节点是否存在
ret = con.has_section('blogs')
print(ret)  # True

# 检查指定节点下参数是否存在
ret = con.has_option('blogs','user_name')
print(ret)    # True

# 删除指定节点下的指定参数
con.remove_option('blogs','user_name')
print(con.has_option('blogs','user_name'))  # False

# 删除指定节点
con.remove_section('blogs')
print(con.has_section('blogs'))  # False

# 删除操作后,需要写入文件
con.write(open('first_ini.ini','w'))