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中实现对list求和及求积

如下所示: # the basic way s = 0 for x in range(10): s += x # the right way s = sum(range(10))...

python3 常见解密加密算法实例分析【base64、MD5等】

本文实例讲述了python3 常见解密加密算法。分享给大家供大家参考,具体如下: 一.使用base64 Base64编码,64指A-Z、a-z、0-9、+和/这64个字符,还有“=”号不...

Python 字符串与数字输出方法

如下所示: x = 3 print(x+"nihao") 这样会报错 x = 3 print(x,"nihao") 这样不会报错,额,今天发现的一个小知识,记录一下 以上这篇...

Python实现的rsa加密算法详解

Python实现的rsa加密算法详解

本文实例讲述了Python实现的rsa加密算法。分享给大家供大家参考,具体如下: 算法过程 1. 随意选择两个大的质数p和q,p不等于q,计算N=pq。 2. 根据欧拉函数,不大于N且与...

Python 类属性与实例属性,类对象与实例对象用法分析

Python 类属性与实例属性,类对象与实例对象用法分析

本文实例讲述了Python 类属性与实例属性,类对象与实例对象用法。分享给大家供大家参考,具体如下: demo.py(类属性,所有实例对象共用类属性): # 定义工具类 继...