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

首先附上 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+"))

(完,待续)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值