Python读写ini文件的方法

onfigparser和ConfigParser在python中用来读取ini类型的配置文件的,提供很多方便的API来使用。

  • configparser: 在python3中的包名
  • ConfigParser:在python2中的包名
#-*-encoding=utf-8-*-
# 测试ConfigParser
import os
import ConfigParser

# 初始化
conf = ConfigParser.ConfigParser()

# 配置文件的绝对路径
conf_path = os.path.dirname(os.path.realpath(__file__)) + "/config.ini"
print(conf_path)
# 读取配置文件
conf.read(conf_path)

"""
读取配置信息
"""
# 查看配置中的所有section
sections = conf.sections()
# print sections

# 返回所有section和序列
sub_conf = conf.options("DOCKER")
print sub_conf

# 返回section中option的值
value_sub_conf = conf.get("DOCKER", "sit")
print value_sub_conf
1、config=ConfigParser.ConfigParser()  
创建ConfigParser实例  
  
2、config.sections()  
返回配置文件中节序列  
  
3、config.options(section)  
返回某个项目中的所有键的序列  
  
4、config.get(section,option)  
返回section节中,option的键值  
  
5、config.add_section(str)  
添加一个配置文件节点(str)  
  
6、config.set(section,option,val)  
设置section节点中,键名为option的值(val)  
  
7、config.read(filename)  
读取配置文件  
  
8、config.write(obj_file)  
写入配置文件  

综合实例

#coding=utf-8  
  
import ConfigParser  
  
def writeConfig(filename):  
    config = ConfigParser.ConfigParser()  
    # set db  
    section_name = 'db'  
    config.add_section( section_name )  
    config.set( section_name, 'dbname', 'MySQL')  
    config.set( section_name, 'host', '127.0.0.1')  
    config.set( section_name, 'port', '80')  
    config.set( section_name, 'password', '123456')  
    config.set( section_name, 'databasename', 'test')  
  
    # set app  
    section_name = 'app'  
    config.add_section( section_name )  
    config.set( section_name, 'loggerapp', '192.168.20.2')  
    config.set( section_name, 'reportapp', '192.168.20.3')  
  
    # write to file  
    config.write( open(filename, 'a') )  
  
def updateConfig(filename, section, **keyv):  
    config = ConfigParser.ConfigParser()  
    config.read(filename)  
    print config.sections()  
    for section in config.sections():  
        print "[",section,"]"  
        items = config.items(section)  
        for item in items:  
            print "\t",item[0]," = ",item[1]  
    print config.has_option("dbname", "MySQL")  
    print config.set("db", "dbname", "11")  
    print "..............."  
    for key in keyv:  
        print "\t",key," = ", keyv[key]  
    config.write( open(filename, 'r+') )  
  
if __name__ == '__main__':  
    file_name = 'test.ini'  
    writeConfig(file_name)  
    updateConfig(file_name, 'app', reportapp = '192.168.100.100')  
    print "end__"  

Python读写ini文件的方法


本文实例讲述了Python读写ini文件的方法。分享给大家供大家参考。具体如下:

比如有一个文件update.ini,里面有这些内容:

1

2

3

4

5

6

7

8

[ZIP]

EngineVersion=0

DATVersion=5127

FileName=dat-5127.zip

FilePath=/pub/antivirus/datfiles/4.x/

FileSize=13481555

Checksum=6037,021E

MD5=aaeb519d3f276b810d46642d782d8921

那就可以通过下面这些代码得到MD5的值,简单吧

1

2

3

4

5

6

7

#!/usr/bin/env python

# -*- coding: utf-8 -*-

import ConfigParser

config = ConfigParser.ConfigParser()

config.readfp(open('update.ini'))

a = config.get("ZIP","MD5")

print a

写也很简单:

1

2

3

4

5

6

7

8

9

10

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

修改也不难(添加内容):

1

2

3

4

5

6

7

8

#!/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+改成其他方式,看看结果:)

修改内容:

1

2

3

4

5

6

7

#!/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+"))

删除部分可以看文档

remove_option( section, option)
Remove the specified option from the specified section. If the section does not exist, raise NoSectionError. If the option existed to be removed, return True; otherwise return False. New in version 1.6.
remove_section( section)
Remove the specified section from the configuration. If the section in fact existed, return True. Otherwise return False.

你可能感兴趣的:(——Python)