python写配置文件方法,Python 操作配置文件汇总

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]

age=21

name=chen

sex=male

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

from __future__ import with_statement

import ConfigParser

config=ConfigParser.ConfigParser()

with open(''testcfg.cfg'',''rw'') as cfgfile:

config.readfp(cfgfile)

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

age=config.get(''info'',''age'')

print name

print age

config.set(''info'',''sex'',''male'')

config.set(''info'',''age'',''21'')

age=config.get(''info'',''age'')

print name

print age

首先config=ConfigParser.ConfigParser()

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

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

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

读文件

Python代码

fromconfigobjimportConfigObj

config = ConfigObj(filename)

#

value1 = config['keyword1']

value2 = config['keyword2']

#

section1 = config['section1']

value3 = section1['keyword3']

value4 = section1['keyword4']

#

# you could also write

value3 = config['section1']['keyword3']

value4 = config['section1']['keyword4']from configobj import ConfigObj

config = ConfigObj(filename)

#

value1 = config['keyword1']

value2 = config['keyword2']

#

section1 = config['section1']

value3 = section1['keyword3']

value4 = section1['keyword4']

#

# you could also write

value3 = config['section1']['keyword3']

value4 = config['section1']['keyword4']

写文件

Python代码

fromconfigobjimportConfigObj

config = ConfigObj()

config.filename = filename

#

config['keyword1'] = value1

config['keyword2'] = value2

#

config['section1'] = {}

config['section1']['keyword3'] = value3

config['section1']['keyword4'] = value4

#

section2 = {

'keyword5': value5,

'keyword6': value6,

'sub-section': {

'keyword7': value7

}

}

config['section2'] = section2

#

config['section3'] = {}

config['section3']['keyword 8'] = [value8, value9, value10]

config['section3']['keyword 9'] = [value11, value12, value13]

#

config.write()from configobj import ConfigObj

config = ConfigObj()

config.filename = filename

#

config['keyword1'] = value1

config['keyword2'] = value2

#

config['section1'] = {}

config['section1']['keyword3'] = value3

config['section1']['keyword4'] = value4

#

section2 = {

'keyword5': value5,

'keyword6': value6,

'sub-section': {

'keyword7': value7

}

}

config['section2'] = section2

#

config['section3'] = {}

config['section3']['keyword 8'] = [value8, value9, value10]

config['section3']['keyword 9'] = [value11, value12, value13]

#

config.write()

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值