有趣生活

当前位置:首页>科技>python学习笔记文件读写发现Python读写ini配置文件

python学习笔记文件读写发现Python读写ini配置文件

发布时间:2026-06-18阅读(1)

导读Windows操作系统经常使用ini文件保存软件配置信息,例如微信中的plugin_info.ini,我来为大家科普一下关于python学习笔记文件读写?以....

Windows操作系统经常使用ini文件保存软件配置信息,例如微信中的plugin_info.ini,我来为大家科普一下关于python学习笔记文件读写?以下内容希望对你有帮助!

python学习笔记文件读写(发现Python读写ini配置文件)

python学习笔记文件读写

Windows操作系统经常使用ini文件保存软件配置信息,例如微信中的plugin_info.ini。

ini文件包含一个或者多个section,每个section包含一个或者多个格式为"key=value"的键值对。

默认情况下小节名对大小写敏感而键值对大小写不敏感

键和值开头和末尾的空格会被移除。

注释使用英文 # 或者 ;

Python内置configparser 类可以读取和写入这种文件。

[Simple Values]key=valuespaces in keys=allowedspaces in values=allowed as wellspaces around the delimiter = obviouslyyou can also use : to delimit keys from values[All Values Are Strings]values like this: 1000000or this: 3.14159265359are they treated as numbers? : nointegers, floats and booleans are held as: stringscan use the API to get converted values directly: true[Multiline Values]chorus: Im a lumberjack, and Im okay I sleep all night and I work all day[No Values]key_without_valueempty string value here =[You can use comments]# like this; or this

构造一个字典对象,其中包含要写到ini文件中的键值对

import configparserconfig = configparser.ConfigParser()config[DEFAULT] = {ServerAliveInterval: 45, Compression: yes, CompressionLevel: 9}config[bitbucket.org] = {}config[bitbucket.org][User] = hgconfig[topsecret.server.com] = {}topsecret = config[topsecret.server.com]topsecret[Port] = 50022 # mutates the parsertopsecret[ForwardX11] = no # same hereconfig[DEFAULT][ForwardX11] = yeswith open(rd:\app.ini, w) as configfile: config.write(configfile)

执行后得到的ini文件

[DEFAULT]serveraliveinterval = 45compression = yescompressionlevel = 9forwardx11 = yes[bitbucket.org]user = hg[topsecret.server.com]port = 50022forwardx11 = no

configparser并不会猜测配置文件中值的类型,而总是将它们在内部存储为字符串,你需要自己进行强制转换。

但是bool(False) 仍然会是 True。 为解决这个问题configparser还提供了 getboolean()。 这个方法对大小写不敏感并可识别 yes/no, on/off, true/false 和 1/0 1 等布尔值。

此外configparser还提供了getint() 和 getfloat() 方法

config = configparser.ConfigParser()config.read(rd:\app.ini)config.sections()for key in config[bitbucket.org]: print(key)config[DEFAULT][Compression]topsecret = config[topsecret.server.com]topsecret[ForwardX11]

添加section

import configparserconfig = configparser.ConfigParser()config.add_section("baidu.com")config["baidu.com"]["port"] = 80with open(rd:\app.ini, a) as configfile: config.write(configfile)

此外,还有删除section方法:remove_section(section)

删除option方法:remove_option(section, option)

注意

configparser不能识别键值对中的百分号%

例如如果compressionlevel的值为"%9"

[DEFAULT]serveraliveinterval = 45compression = yescompressionlevel = %9forwardx11 = yes

那么执行下面的代码时就会抛出异常

print(config["DEFAULT"]["compressionlevel"])

InterpolationSyntaxError: % must be followed by % or (, found: %9

解决方法是使用RawConfigParser而不是configparser

config = configparser.RawConfigParser()

TAGS标签:  python  学习  笔记  文件  读写  python学习笔记

Copyright © 2024 有趣生活 All Rights Reserve吉ICP备19000289号-5 TXT地图HTML地图XML地图