Python读写,以及修改my.ini文件--针对Python3.0版本

来源:互联网 发布:java中强制类型转换 编辑:程序博客网 时间:2024/06/07 15:40

首先附上 my.ini里面的内容:

[book]
title = the python standard library
author = fredrik lundh


[ematter]
pages = 250


[md5]
value = kingsoft




读取ini文件

__author__ = 'minggxu9'  #!/usr/bin/env python# -*- coding: utf-8 -*-'''The ConfigParser module has been renamed to configparser in Python 3.0. The 2to3 tool will automaticallyadapt imports when converting your sources to 3.0.参考网址:http://docs.python.org/library/configparser.html'''import configparser config = configparser.ConfigParser()config.readfp(open('../my.ini'))   #可以使用相对路径获取a = config.get("book","author")print(a)
然后追加内容:
__author__ = 'minggxu9'import configparserconfig = configparser.ConfigParser()#写文件config.add_section("book")config.set("book", "title", "the python standard library")config.set("book", "author", "fredrik lundh")config.add_section("ematter")config.set("ematter", "pages", "250")#注意后面的键值必湏为字符串类型# write to fileconfig.write(open('../my.ini', "w"))#写权限


然后追加里面的值:
__author__ = 'minggxu9'#!/usr/bin/env python# -*- coding: utf-8 -*-import configparserconfig = configparser.ConfigParser()config.read('../my.ini')a = config.add_section("md5")config.set("md5", "value", "1234")config.write(open('1.ini', "r+")) #可以把r+改成其他方式,看看结果:) r+表示以追加的方式,也可以用a  ,append


最后修改里面的键值:


__author__ = 'minggxu9'#!/usr/bin/env python# -*- coding: utf-8 -*-import configparserconfig = configparser.ConfigParser()config.read('../my.ini')config.set("md5", "value", "kingsoft") #这样md5就从1234变成kingsoft了config.write(open('1.ini', "r+"))

(完,待续)