python编程实践:配置文件ini的读取写入

我们编写软件的时候,经常要用到配置文件,而配置文件一般为ini或xml或json文件。

本文重点阐述配置文件ini的读取方法和技巧,xml和json文件的具体读取方法和技巧下个文章里阐述。

ini文件以节(section)和键(key)构成,常用于微软Windows操作系统中。这种配置文件的文件扩展名多为ini,故名。由于ini文件是纯文本格式,所以可以用任何纯文本编辑器来进行编辑其内容。

配置文件test.ini 的内容,使用记事本notepad 打开

ini配置文件格式

节(section)

节用方括号括起来,单独占一行,例如:

[section]

键(key)

键(key)又名属性(property),单独占一行用等号连接键名和键值,例如:

name=value

注释(comment)

注释使用英文分号(;)开头,单独占一行。在分号后面的文字,直到该行结尾都全部为注释,例如:

; comment text

ini配置文件读取

下面给大家介绍一下,用python怎么快速读ini配置文件

使用pip install configparser命令安装configparser模块。

import os, sys
import configparser
#dirname:程序所在的目录, filename: 程序名
dirname,filename = os.path.split(os.path.abspath(sys.argv[0]))  
inifilename = dirname+'/test.ini'  #为什么这样表述呢?

config = configparser.ConfigParser()

#test.ini 的内容如上图所示
config.read(inifilename)

#获得num的值,整数
num = config.getint("table","num")
print(num)  #8
#获得tablename的值,字符串
tablename = config.get("table","tablename")
print(tablename)  #cs_forecast
#获得urlstr的值,字符串
urlstr = config.get("city","urlstr")
print(urlstr)  #http://www.weather.com.cn/weather/%%s.shtml
#获得citystr的值,字符串
citystr = config.get("city","citystr")
print(citystr)  # 北京,武汉,兰州,长沙

#获取所有的selections
sections = config.sections()
print(sections) #  ['table', 'city']

#获取指定sections下的所有options
options = config.options("table")
print(options)  # ['num', 'city']

#判断是否含有指定selection 或 option
print(config.has_section("table"))  # True
print(config.has_option("table", "flag"))  # False

ini配置文件写信息参数

除了ini配置文件读取信息参数外,有时候根据业务场景的不同,还需要将有关信息写入ini配置文件,以便下次需要的时候读取。

import os, sys
import configparser
#dirname:程序所在的目录, filename: 程序名
dirname,filename = os.path.split(os.path.abspath(sys.argv[0]))  
inifilename = dirname+'/test.ini'

config = configparser.ConfigParser()

#test.ini 的内容如上图所示
config.read(inifilename)

config.add_section("test_title")  # 设置option的值
config.set("test_title", "key1", "1111111111")  # 注意这里的selection一定要先存在!
config.set("test_title", "key2", "2222222222")

config.remove_section("city")  # 移除指定selection

config.remove_option("table", "num")  # 移除指定selection下的option

with open(inifilename, "w+") as f:
    config.write(f)

需要注意的一个细节

如果某个section已经存在了,如上例,在写入的时候不能够再使用config.add_section(‘test_title’)这个函数了,这样会报错,所以,我们需要进行判断,先判断test_title是否存在,然后再进行操作。

if 'test_title' not in config.sections():
    config.add_section('test_title')

这样就可以在 test_title 这个section下面进行追加操作了。

阅读完毕,诚邀您点击一下“关注”按钮,方便以后持续为您推送此类文章,同时也便于您进行讨论与分享,您的支持是我们坚持创作的动力~~~

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值