Python操作配置信息的工具类ConfigParser的使用讲解
2016-08-23 21:04
543 查看
.ini 文件是Initialization File的缩写,即初始化文件 ,是windows的系统配置文件所采用的存储格式,统管windows的各项配置,一般用户就用windows提供的各项图形化管理界面就可实现相同的配置了。但在某些情况,还是要直接编辑.ini才方便,一般只有很熟悉windows才能去直接编辑。开始时用于WIN3X下面,WIN95用注册表代替,以及后面的内容表示一个节,相当于注册表中的键。 除了windows2003很多其他操作系统下面的应用软件也有.ini文件,用来配置应用软件以实现不同用户的要求。一般不用直接编辑这些.ini文件,应用程序的图形界面即可操作以实现相同的功能。它可以用来存放软件信息,注册表信息等。 1.基本的读取配置文件 1)直接读取ini文件内容
import ConfigParser config = ConfigParser.RawConfigParser(allow_no_value=True) config.read('test.ini') print config #<ConfigParser.RawConfigParser instance at 0x0240F9B8>
2)得到所有的section,并以list列表的形式返回
print config.sections() #['login_account_info']
3)得到该section的所有option,并以list列表的形式返回
sects = config.sections() for row in sects: print config.options(row) #['login_username', 'login_uid', 'login_password', 'cookies_file']
4)得到该section的所有键值对,返回的数据是tupple的list集合
sects = config.sections() for row in sects: # print config.options(row) print config.items(row) #[('login_username', 'ur_weibo_account_id_here'), ('login_uid', '1248521225'), ('login_password', 'ur_weibo_account_password_here'), ('cookies_file', 'weibo_cookies.dat')]
5)get(section,option)得到section中option的值,返回为string类型
print config.get('login_account_info', 'cookies_file')
6)getint(section,option) 得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat()
print config.getint('login_account_info','test_int')
2.基本的写入配置文件 1)add_section(section) 添加一个新的section 2)set( section, option, value) 对section中的option进行设置,需要调用write将内容写入配置文件。
config.add_section('cainiao') config.set('cainiao', 'test_float', '23.67') config.set('cainiao', 'test_float', '23.67123') config.write(open('test1.ini', 'w+'))
输出的结果是
[cainiao] test_float = 23.67123
还请大神多多指导
相关文章推荐
- Python配置工具类ConfigParser使用
- 使用配置文件来存储数据库链接信息时---工具类的编写
- Python文件配置configParser使用
- python操作三大主流数据库(3)python操作mysql③python操作mysql的orm工具sqlaichemy安装配置和使用
- Python中使用ConfigParser解析ini配置文件实例
- python 提供INI配置文件的操作 ConfigParser
- python读取读取配置文件信息操作代码
- Python使用ConfigParser模块操作配置文件的方法
- python3使用configparser读取带有中文的配置文件出现UnicodeDecodeError错误
- python列表操作实例源码讲解(创建、使用、更新、删除)
- python操作配置文件configparser 增删改查
- Python语言学习讲解七:使用traceback获取详细的异常信息
- jdbc数据库连接管理封装工具类,不同使用属性文件配置数据库连接信息(2)
- 【新手入门】Python下不喜欢使用ConfigParser去读取配置文件的Java developer
- python读取读取配置文件信息操作代码
- Python的字符串模板(Template)使用操作实例讲解
- python Sublime Text3的使用基本配置操作&&SublimeREPL插件的安装及快捷键设置
- python读取读取配置文件信息操作代码
- Python语言学习讲解七:使用traceback获取详细的异常信息