python - configparser模块

来源:趣味经验馆 4.75K

<link rel="stylesheet" href="https://js.how234.com/third-party/SyntaxHighlighter/shCoreDefault.css" type="text/css" /><script type="text/javascript" src="https://js.how234.com/third-party/SyntaxHighlighter/shCore.js"></script><script type="text/javascript"> SyntaxHighlighter.all(); </script>

python configparser模块是什么?让我们一起来了解下吧:

ConfigParser模块在python3中修改为configparser.这个模块定义了一个ConfigParser类,该类的作用是使用配置文件生效,配置文件的格式和windows的INI文件的格式相同.

该模块的作用 就是使用模块中的RawConfigParser()、ConfigParser()、 SafeConfigParser()这三个方法(三者择其一),创建一个对象使用对象的方法对指定的配置文件做增删改查操作。

配置文件有不同的片段组成和Linux中repo文件中的格式类似:

[section] name=value或者name: value"#" 和";" 表示注释[DEFAULT] #设置默认的变量值,初始化

[My Section]foodir: %(dir)s/whateverdir=froblong: this value continues   in the next line

%(dir)s 会被frob代替。默认值会以字典的形式传递给ConfigParser的构造器,section一般存放的内置目录下,如果切换到其他的目录需求指定存放位置。

方法

下面这三种方式使用时,切记注意

在调用这三个函数时,切记这三个函数会将调用optionxform(),在传递键值对数据时,会将键名 全部转化为小写。

RawConfigParser()

ConfigParser.RawConfigParser([defaults[, dict_type[, allow_no_value]]]) defaults : 如果指定默认值,则使用默认值的键值对dict_type:使用新的section的键值对allow_no_value :默认是False,如果是True,表示可以接收空值(None)return:对象

不支持可变参数,在section中不能存在%()s

ConfigParser()

ConfigParser.ConfigParser([defaults[, dict_type[, allow_no_value]]])

在default中必须出现%()s

SafeConfigParser()

 ConfigParser.SafeConfigParser([defaults[, dict_type[, allow_no_value]]])

更加智能化,在section中是否存在%()s会自动判断

传递参数使用函数optionxform(),foo %(bar)s 和 foo %(BAR)s是相同的,optionxform()会将大写字母全部转换为小写。

python configparser模块

热门标签