分享

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

 禁忌石 2023-09-01 发布于浙江

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

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

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

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

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

ini配置文件格式

节(section)

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

[section]

键(key)

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

name=value

注释(comment)

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

; comment text

ini配置文件读取

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

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

import os, sysimport 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) # 北京,武汉,兰州,长沙#获取所有的selectionssections = config.sections()print(sections) # ['table', 'city']#获取指定sections下的所有optionsoptions = config.options('table')print(options) # ['num', 'city']#判断是否含有指定selection 或 optionprint(config.has_section('table')) # Trueprint(config.has_option('table', 'flag')) # False

ini配置文件写信息参数

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

import os, sysimport 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')  # 移除指定selectionconfig.remove_option('table', 'num')  # 移除指定selection下的optionwith 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下面进行追加操作了。

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

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约