Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4998969
  • 博文数量: 921
  • 博客积分: 16037
  • 博客等级: 上将
  • 技术积分: 8469
  • 用 户 组: 普通用户
  • 注册时间: 2006-04-05 02:08
文章分类

全部博文(921)

文章存档

2020年(1)

2019年(3)

2018年(3)

2017年(6)

2016年(47)

2015年(72)

2014年(25)

2013年(72)

2012年(125)

2011年(182)

2010年(42)

2009年(14)

2008年(85)

2007年(89)

2006年(155)

分类: Python/Ruby

2011-02-15 22:56:03

 

ini文件的格式参照了这里 
也参考了Python的ConfigParser模块的文档

IniFileParser.py


#!C:\Python24\python.exe

import re
import string

NoSectionException = 'NoSectionException'
NoKeyException = 'NoKeyException'

class IniFileParser:
    '''parse ini file described in . no functions for write, only read. :)'''
    def __init__(self):
        self.section_obj = dict()

    def load(self, filename):
        f = open(filename, 'r')
        while 1:
            line = f.readline()
            if not line: break
            line = line.strip('\n')
            line = line.strip()
            # skip comments
            if line == "" or line.startswith(';') or line.startswith('#'):
                continue
            match_section = re.compile(r'^\[([\w\s\.]*)\]$').match(line)
            if match_section:   # section name line
                line = match_section.group(1) # get section name
                sec_keys = dict()
                self.section_obj[line] = sec_keys
            else:               # key=value line
                re_comment = re.compile(r'[;#].*')
                line = re_comment.sub('', line) # remove comments in line
                [key, value] = map(string.strip, line.split('=', 1))
                sec_keys[key] = value
                
        f.close()

    def sections(self):
        result = self.section_obj.keys()
        result.sort()
        return result

    def has_section(self, section):
        return section in self.section_obj.keys()

    def keys(self, section):
        if not self.has_section(section): raise NoSectionException
        result = self.section_obj[section].keys()
        result.sort()
        return result

    def has_key(self, section, key):
        return self.section_obj[section].has_key(key)

    def get_value(self, section, key):
        if not self.has_section(section): raise NoSectionException
        if not self.has_key(section, key): raise NoKeyException
        return self.section_obj[section][key]



Unit Test: TestIniFileParser.py


#!C:\Python24\python.exe

import unittest
from IniFileParser import *

class TestIniFileParser(unittest.TestCase):
    def setUp(self):
        self.ini = IniFileParser()
        self.ini.load('test.ini')

    def testsections(self):
        self.assertEqual(self.ini.sections(), ['section1', 'section2'])

    def testhassections(self):
        self.assertTrue(self.ini.has_section('section1'))
        self.assertTrue(self.ini.has_section('section2'))
        self.assertFalse(self.ini.has_section('section3'))

    def testkeys(self):
        self.assertEqual(self.ini.keys('section1'), ['var1', 'var2'])
        self.assertEqual(self.ini.keys('section2'), ['var1', 'var2'])
        self.assertRaises(NoSectionException, self.ini.keys, 'section3')

    def testhaskey(self):
        self.assertTrue(self.ini.has_key('section1', 'var1'))
        self.assertTrue(self.ini.has_key('section1', 'var2'))
        self.assertTrue(self.ini.has_key('section2', 'var1'))
        self.assertTrue(self.ini.has_key('section2', 'var2'))

    def testgetvalue(self):
        self.assertEqual(self.ini.get_value('section1', 'var1'), 'foo')
        self.assertEqual(self.ini.get_value('section1', 'var2'), 'doodle')
        self.assertEqual(self.ini.get_value('section2', 'var1'), 'baz')
        self.assertEqual(self.ini.get_value('section2', 'var2'), 'shoodle')
        self.assertRaises(NoSectionException, self.ini.get_value, 'section3', 'var1')
        self.assertRaises(NoKeyException, self.ini.get_value, 'section1', 'var3')

if __name__ == '__main__':
    #unittest.main()
    suite = unittest.makeSuite(TestIniFileParser)
    unittest.TextTestRunner(verbosity=2).run(suite)



ini file for test: test.ini
引用:
[section1]

; some comment on section1
var1 = foo
var2 = doodle ; some comment on section1.var2

[section2]

# some comment on section2
var1 = baz # some comment on section2.var1
var2 = shoodle

# [section3]
# var1 = bar
; var2 = 

################################################

python读写ini配置文件
ixamail.ini

[host]
smtp_server=smtp.126.com
smtp_username=aspphp
smtp_password=123456
[task]
task_url=


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import ConfigParser
config = ConfigParser.ConfigParser()
config.readfp(open('ixamail.ini))
a = config.get("host","smtp_server")
print a

写文件也简单

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')

a = 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+"))

#####################################################

    本文主要讲述的是python 读写配置文件的例子以及相关代码的介绍,以及如何修改配置中的变量的值,以下是相关的介绍。

    python 读写配置文件在实际应用中具有十分强大的功能,在实际的操作中也有相当简捷的操作方案,以下的文章就是对python 读写配置文件的具体方案的介绍,望你浏览完下面的文章会有所收获。

    python 读写配置文件ConfigParser模块是python自带的读取配置文件的模块.通过他可以方便的读取配置文件. 这篇文章简单介绍一下python 读写配置文件的方法.

    配置文件.顾名思议就是存放配置的文件.下面是个例子

         [info]  
    1. age = 21 
    2. name = chen 
    3. sex = male 

    其中[ ] 中的info是这段配置的名字下面age,name都是属性下面的代码演示了如何读取python 读写配置文件.和修改配置中变量的值

    1. from __future__ import with_statement  
    2. import ConfigParser  
    3. config=ConfigParser.ConfigParser()  
    4. with open(''testcfg.cfg'',''rw'') as cfgfile:  
    5. config.readfp(cfgfile)  
    6. name=config.get(''info'',''name'')  
    7. age=config.get(''info'',''age'')  
    8. print name  
    9. print age  
    10. config.set(''info'',''sex'',''male'')  
    11. config.set(''info'',''age'',''21'')  
    12. age=config.get(''info'',''age'')  
    13. print name  
    14. print age 

    首先

    1. config=ConfigParser.ConfigParser() 

    得到一个配置config对象.下面打开一个配置文件 cfgfile. 用readfp()读取这个文件.这样配置的内容就读到config对象里面了.接下来一个问题是如何读取值.常用的方法是get() 和getint() . get()返回文本. getint()返回整数

    1. name=config.get(''info'',''name'')  

    意思就是.读取config中info段中的name变量值.最后讲讲如何设置值.使用set(段名,变量名,值) 来设置变量.config.set(''info'',''age'',''21'') 表示把info段中age变量设置为21. 就这么简单. 以上就是对python 读写配置文件的相关介绍。

    #####################################################################

      python优秀的库资源确实很多,最近发现了一个简单而又强大的读写配置文件的lib,地址在这里 ,我觉得最大的亮点在于自带的格式校验功能,并且支持复杂的嵌套格式,而且使用起来也相当的简便,按教程来如下:

      读文件

      Python代码
       
      1. from configobj import ConfigObj   
      2. config = ConfigObj(filename)   
      3. #   
      4. value1 = config['keyword1']   
      5. value2 = config['keyword2']   
      6. #   
      7. section1 = config['section1']   
      8. value3 = section1['keyword3']   
      9. value4 = section1['keyword4']   
      10. #   
      11. # you could also write   
      12. value3 = config['section1']['keyword3']   
      13. value4 = config['section1']['keyword4']  

       

      写文件

      Python代码
       
      1. from configobj import ConfigObj   
      2. config = ConfigObj()   
      3. config.filename = filename   
      4. #   
      5. config['keyword1'] = value1   
      6. config['keyword2'] = value2   
      7. #   
      8. config['section1'] = {}   
      9. config['section1']['keyword3'] = value3   
      10. config['section1']['keyword4'] = value4   
      11. #   
      12. section2 = {   
      13.     'keyword5': value5,   
      14.     'keyword6': value6,   
      15.     'sub-section': {   
      16.         'keyword7': value7   
      17.         }   
      18. }   
      19. config['section2'] = section2   
      20. #   
      21. config['section3'] = {}   
      22. config['section3']['keyword 8'] = [value8, value9, value10]   
      23. config['section3']['keyword 9'] = [value11, value12, value13]   
      24. #   
      25. config.write()  


      更详细的信息可以参阅下doc,蛮详尽的


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