Leif160519的blog Leif160519的blog

——————

目录
Python读写ini文件的方法
/  

Python读写ini文件的方法

本文实例讲述了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+"))

“The first 90% of the code accounts for the first 90% of the development time. The remaining 10% of the code accounts for the other 90% of the development time.” – Tom Cargill

标  题Python读写ini文件的方法
作  者Leif160519
出  处https://github.icu/articles/2019/10/08/1570523343222.html
关于博主:坐标南京,运维工程师,如有问题探讨可以直接下方留言。
声援博主:如果您觉得文章对您有帮助,可以评论、订阅、收藏。您的鼓励是博主的最大动力!