首先附上 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 automatically
adapt 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 configparser config = 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 file config.write(open('../my.ini', "w")) #写权限
然后追加里面的值:
__author__ = 'minggxu9' #!/usr/bin/env python # -*- coding: utf-8 -*- import configparser config = 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 configparser config = configparser.ConfigParser() config.read('../my.ini') config.set("md5", "value", "kingsoft") #这样md5就从1234变成kingsoft了 config.write(open('1.ini', "r+"))
(完,待续)