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

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=value spaces in keys=allowed spaces in values=allowed as well spaces around the delimiter = obviously you can also use : to delimit keys from values [All Values Are Strings] values like this: 1000000 or this: 3.14159265359 are they treated as numbers? : no integers, floats and booleans are held as: strings can use the API to get converted values directly: true [Multiline Values] chorus: I'm a lumberjack, and I'm okay I sleep all night and I work all day [No Values] key_without_value empty string value here = [You can use comments] # like this ; or this

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

import configparser config = configparser.ConfigParser() config['DEFAULT'] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9'} config['bitbucket.org'] = {} config['bitbucket.org']['User'] = 'hg' config['topsecret.server.com'] = {} topsecret = config['topsecret.server.com'] topsecret['Port'] = '50022' # mutates the parser topsecret['ForwardX11'] = 'no' # same here config['DEFAULT']['ForwardX11'] = 'yes' with open(r'd:\app.ini', 'w') as configfile: config.write(configfile)

执行后得到的ini文件

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

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

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

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

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

添加section

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

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

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

注意

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

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

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

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

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

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

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

config = configparser.RawConfigParser()

,

免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。文章投诉邮箱:anhduc.ph@yahoo.com

    分享
    投诉
    首页