Chinaunix首页 | 论坛 | 博客
  • 博客访问: 447322
  • 博文数量: 121
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1101
  • 用 户 组: 普通用户
  • 注册时间: 2014-03-20 19:29
个人简介

http://meetbill.github.io/

文章分类

全部博文(121)

我的朋友

分类: Python/Ruby

2015-08-13 11:34:13

假如存在一个test.ini文件,内容为:
[test.ini文件内容] view plaincopy
  1. [Default]
  2. String=Test

1读取ini文件
[程序内容] view plaincopy
  1. # -*- coding: cp936 -*-
  2. import ConfigParser
  3.  
  4. config = ConfigParser.ConfigParser()
  5. config.readfp(open('test.ini'))
  6.  
  7. print config.get("Default","String")

2写入ini文件
[程序内容] view plaincopy
  1. # -*- coding: cp936 -*-
  2. import ConfigParser
  3.  
  4. config = ConfigParser.ConfigParser()
  5.  
  6. # 设置section段及对应的值
  7. config.add_section("Default") 
  8. config.set("Default","String","Test")
  9.  
  10. #写入文件
  11. config.write(open('test.ini',"w"))

3修改ini文件
[程序内容] view plaincopy
  1. # -*- coding: cp936 -*-
  2. import ConfigParser
  3.  
  4. config = ConfigParser.ConfigParser()

  5. config.read('test.ini')
  6. #看是否存在该section,不存在则创建
  7. if not config.has_section("Default"):
  8.     temp = config.add_section("")
  9.  
  10. config.set("Default", "String", "Test")
  11. config.write(open('1.ini', "r+")) 



# -*- coding:gbk -*-
import ConfigParser, os
class INIFILE:
    def __init__(self, filename):
        self.filename = filename
        self.initflag = False
        self.cfg = None
        self.readhandle = None
        self.writehandle = None

    def Init(self):
        self.cfg = ConfigParser.ConfigParser()
        try:
            self.readhandle = open(self.filename, 'r')
            self.cfg.readfp(self.readhandle)
            self.writehandle = open(self.filename, 'w')
            self.initflag = True
        except:
            self.initflag = False
        return self.initflag

    def UnInit(self):
        if self.initflag:
            self.readhandle.close()
            self.writehandle.closse()

    def GetValue(self, Section, Key, Default = ""):
        try:
            value = self.cfg.get(Section, Key)
        except:
            value = Default
        return value

    def SetValue(self, Section, Key, Value):
        try:
            self.cfg.set(Section, Key, Value)
        except:
            self.cfg.add_section(Section)
            self.cfg.set(Section, Key, Value)
            self.cfg.write(self.writehandle)

阅读(637) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~