python读取配置文件configparser

xiaoxiao2021-02-28  10

跟着 http://blog.csdn.net/u011541946/article/details/70174276 博主的博客,了解了一下configparser,自己扩展和百度 了一下写入文件和configparser一些常用方法

可读取写入配置文件

import configparser import os import sys class TestCfigParser(object): config = configparser.ConfigParser() def get_value(self): root_dir = os.path.dirname(os.path.abspath('.')) print(root_dir) file_path = os.path.dirname(os.path.abspath('.'))+'/config/config.ini' #文件路径 self.config.read(file_path) #读文件 browser = self.config.get("browserType","browserName") #key、value类型 url = self.config.get("testServer","URL") for section in self.config.sections(): #尝试用到section、option print(section) for option in self.config.options(section):#k,value section \ option #print(option) print(option+'='+self.config.get(section,option)) #get方法get(section,option) return(browser,url) def set_value(self): file_path = os.path.dirname(os.path.abspath('.')) + '/config/config.ini' self.config.add_section('book') self.config.set('book','title','标题') self.config.set('book','author','作者') self.config.write(sys.stdout) self.config.write( open(file_path, 'a') ) test = TestCfigParser() print(test.get_value()) test.set_value() 在python 3 中模块名字为configparser首字母小写,文章 http://blog.csdn.net/ztf312/article/details/47259805 提到一些常用的方法如下

1、config=configParser.ConfigParser() 创建ConfigParser实例

2、config.sections() 返回配置文件中节序列 3、config.options(section) 返回某个项目中的所有键的序列 4、config.get(section,option) 返回section节中,option的键值 5、config.add_section(str) 添加一个配置文件节点(str) 6、config.set(section,option,val) 设置section节点中,键名为option的值(val) 7、config.read(filename) 读取配置文件 8、config.write(obj_file) 写入配置文件

转载请注明原文地址: https://www.6miu.com/read-450325.html

最新回复(0)