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

相关文章

如何运行.ipynb文件的图文讲解

如何运行.ipynb文件的图文讲解

首先cmd下面输入: pip install jupyter notebook,安装慢的改下pip的源为国内的源 然后cmd中输入: jupyter notebook就会弹出一个页面 先...

Python可变参数会自动填充前面的默认同名参数实例

最近在学习Python的时候遇到一个知识点,在此记录下来 可变参数会自动填充前面的同名默认参数 比如下面这个函数 def add_student(name="Bob", **info...

django+tornado实现实时查看远程日志的方法

大致思路: 1.利用tornado提供的websocket功能与浏览器建立长连接,读取实时日志并输出到浏览器 2.写一个实时读取日志的脚本,利用saltstack远程执行,并把实时日志发...

python实现批量修改文件名代码

python实现批量修改文件名代码

我曾以为,写脚本是很难的,直到我遇到了Python 前言随着国内版权意识的跟进,很多影视音乐资源开始收费,而且度盘又经常随意封杀各种资源,所以,为了保护资源,老司机们越来越倾向于把资源下...

Python 多线程其他属性以及继承Thread类详解

Python 多线程其他属性以及继承Thread类详解

一、线程常用属性 1.threading.currentThread:返回当前线程变量 2.threading.enumerate:返回一个包含正在运行的线程的list,正在运行的线程指...