Python读写ini文件的方法

yipeiwu_com5年前Python基础

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

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

[ZIP]
EngineVersion=0
DATVersion=5127
FileName=dat-5127.zip
FilePath=/pub/antivirus/datfiles/4.x/
FileSize=13481555
Checksum=6037,021E
MD5=aaeb519d3f276b810d46642d782d8921

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

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import ConfigParser
config = ConfigParser.ConfigParser()
config.readfp(open('update.ini'))
a = config.get("ZIP","MD5")
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+"))

删除部分就懒得写了,感兴趣的自己看文档:

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程序设计有所帮助。

相关文章

Python语言检测模块langid和langdetect的使用实例

之前使用数据编码风格检测的模块chardet比较多一点,今天提到的两个模块是检测数据的语言类型,比如是:中文还是英文,模块的使用方法也比较简单,我这里只是简单地使用了一下,因为项目中有这...

python使用xlrd和xlwt读写Excel文件的实例代码

安装模块 如果使用的是Linux系统,并且安装了pip,可以直接使用pip安装xlrd, xlwt: pip install xlwt pip install xlrd 也可以从官...

python测试mysql写入性能完整实例

本文主要研究的是python测试mysql写入性能,分享了一则完整代码,具体介绍如下。 测试环境: (1) 阿里云服务器centos 6.5 (2) 2G内存 (3) 普通硬盘 (4)...

Python下载网络文本数据到本地内存的四种实现方法示例

本文实例讲述了Python下载网络文本数据到本地内存的四种实现方法。分享给大家供大家参考,具体如下: import urllib.request import requests fr...

python实现车牌识别的示例代码

python实现车牌识别的示例代码

某天回家之时,听到有个朋友说起他正在做一个车牌识别的项目 于是对其定位车牌的位置算法颇有兴趣,今日有空得以研究,事实上车牌识别算是比较成熟的技术了, 这里我只是简单实现。 我的思路为:...