python 配置文件生效的模块ConfigeParser
ConfigParser模块在Python3修改为configparser,这个模块定义了一个ConfigeParser类,该类的作用是让配置文件生效。配置文件的格式和window的ini文件相同,大致如下:
【section】
name = value
name:value
用 = 或 : 来赋值
section可以理解为一个模块,比如登录的时候,这个section可以叫login,下面放着username和password
[login] username = pretend_smile password = 123456
该模块主要使用模块中RawConfigParser(),ConfigParser()、SafeConfigParse()这三个方法(三选一),创建一个对象,使用对象的方法对配置文件进行增删改查操作
主要介绍ConfigParser()下的方法
涉及增删改的操作 都需要使用write()方法之后才会生效
add_section():用来新增section
set():用来新增对应section下的某个键值对
get()方法可以获得指定section下某个键的值
import configparser import os pathnow = os.path.realpath(__file__) print(pathnow) pathfather = os.path.split(pathnow)[0] print(pathfather) pathbrother = os.path.join(pathfather,'fanpl.ini') print(pathbrother) config = configparser.ConfigParser() config.read(pathbrother) config.add_section('login') config.set('login','username','1111') config.set('login','password','2222') with open(pathbrother,'w') as configfile: config.write(configfile) print(config.get('login','username'))
read()方法是用来读取配置文件的,如果不加上read()方法,写入是直接从头开始写的,使用了read()之后,是从读取完后的光标开始写入,类似追加模式'a'一样。可能有疑惑,既然有追加模式,直接把with里面的'w'换成'a'就可以,干嘛还要读一次
将上面的代码修改一下,将username和password的值修改一下
import configparser import os pathnow = os.path.realpath(__file__) print(pathnow) pathfather = os.path.split(pathnow)[0] print(pathfather) pathbrother = os.path.join(pathfather,'fanpl.ini') print(pathbrother) config = configparser.ConfigParser() config.read(pathbrother) config.add_section('login') config.set('login','username','3333') config.set('login','password','4444') with open(pathbrother,'w') as configfile: config.write(configfile) print(config.get('login','username'))
会发现username和password的值被修改了,如果使用'a'模式,会发现报错,没有找到login这个section。
就算把上面代码中加上config.add_section('login')也只会在后面进行追加新增,而不会做修改操作
所以考虑到把方法封装的缘故,使用read()和'w'写入模式,来实现追加新增,修改配置文件
sections()方法返回可用的section,默认DEFAULT是不会返回的
username = config.sections() print(username)
options()返回对应section下可用的键
op = config.options("login") print(op)
has_section()方法判断section是否存在,存在返回True,不存在返回False
hs = config.has_section('login') print(hs)
has_option()方法判断section下,某个键是否存在,存在返回True,不存在返回False
hs = config.has_option("login","userame") print(hs)
删除
remove_section()方法删除某个section
remove_option()方法删除某个section下的键
import  configparser
 
config = configparser.ConfigParser()
file = 'D:/PycharmProjects/Vuiki/Config/config.ini'
config.read(file)
config.remove_option('login','username')
config.remove_option('login','password')
config.remove_section('login')
with open(file,'w') as configfile:
      config.write(configfile)
一定要先read()到内存,不然删除报错
--------------------- 
原文:https://blog.csdn.net/a54288447/article/details/81027593 
 
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号