Python写配置文件

 
# -*- encoding: gb2312 -*-
import  ConfigParser
import  string, os, sys

cf 
=  ConfigParser.ConfigParser()
cf.read(
" test.conf " )
#  返回所有的section
=  cf.sections()
print   ' section: ' , s

=  cf.options( " db " )
print   ' options: ' , o

=  cf.items( " db " )
print   ' db: ' , v

print   ' - ' * 60
# 可以按照类型读取出来
db_host  =  cf.get( " db " " db_host " )
db_port 
=  cf.getint( " db " " db_port " )
db_user 
=  cf.get( " db " " db_user " )
db_pass 
=  cf.get( " db " " db_pass " )

#  返回的是整型的
threads  =  cf.getint( " concurrent " " thread " )
processors 
=  cf.getint( " concurrent " " processor " )

print   " db_host: " , db_host
print   " db_port: " , db_port
print   " db_user: " , db_user
print   " db_pass: " , db_pass

print   " thread: " , threads
print   " processor: " , processors
# 修改一个值,再写回去
cf.set( " db " " db_pass " " zhaowei " )
cf.write(open(
" test.conf " " w " ))



# 写文件

import ConfigParser

config 
=
 ConfigParser.ConfigParser()

# set a number of parameters

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('1.ini'"w"))

修改也可以

#!/usr/bin/env python
#
 -*- coding: utf-8 -*-

import ConfigParser

config 
=
 ConfigParser.ConfigParser()

config.read(
'1.ini'
)

= config.add_section("md5"
)

config.set(
"md5""value""1234"
)

config.write(open(
'1.ini'"r+"
))      #可以把r+改成其他方式,看看结果:)

#!/usr/bin/env python
#
 -*- coding: utf-8 -*-

import ConfigParser

config 
=
 ConfigParser.ConfigParser()

config.read(
'1.ini'
)

config.set(
"md5""value""kingsoft"
)     #这样md5就从1234变成kingsoft了

config.write(open(
'1.ini'"r+"))

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值