python configparser模块的应用

1、获取所有section

import configparser

 

config = configparser.ConfigParser()

config .read('文件所在的路径',encoding='utf-8')

ret=config .sections()

print(ret)

 

2、获取指定section下所有的键值对

import configparser

 

config = configparser.ConfigParser()

config.read('文件所在路径',encoding='utf-8')

ret=config.items('section1')

print(ret)

 

3、获取指定section下所有的键

import configparser

 

config = configparser.ConfigParser()

config.read('文件所在路径',encoding='utf-8')

ret = config.options('section1')

print(ret)

 

4、获取指定section下指定key的值

import configparser 

 

config = configparser.ConfigParser()

config.read('文件所在路径',encoding = 'utf-8')

ret = config.get('section1','K1')

print(ret)

 

5、检查、删除、添加section

import configparser 

 

config = configparser.ConfigParser()

config.read('文件所在路径',encoding = 'utf-8')

检查section

has_sec = config.has_section('section1')

print(has_sec)

添加section

config.add_section('section1')

config.write(open('文件所在路径',''w))

删除section

config.remove_section('section1')

config.write(open('文件所在路径',''w))

 

posted @ 2023-07-03 15:22  博客新手818  阅读(39)  评论(0)    收藏  举报