python读写ini文件示例(python读写文件)


Posted in Python onMarch 25, 2014

很类似java的properties文件

xml文件

db_config.ini
[baseconf]
host=127.0.0.1
port=3306
user=root
password=root
db_name=evaluting_sys
[concurrent]
processor=20

对应的python代码

#!/usr/bin/python
# -*- coding:utf-8 -*-
#author: lingyue.wkl
#desc: use to db ops
#---------------------
#2012-02-18 created
#---------------------
import sys,os
import ConfigParser
class Db_Connector:
  def __init__(self, config_file_path):
    cf = ConfigParser.ConfigParser()
    cf.read(config_file_path)
    s = cf.sections()
    print 'section:', s
    o = cf.options("baseconf")
    print 'options:', o
    v = cf.items("baseconf")
    print 'db:', v
    db_host = cf.get("baseconf", "host")
    db_port = cf.getint("baseconf", "port")
    db_user = cf.get("baseconf", "user")
    db_pwd = cf.get("baseconf", "password")
    print db_host, db_port, db_user, db_pwd
    cf.set("baseconf", "db_pass", "123456")
    cf.write(open("config_file_path", "w"))
if __name__ == "__main__":
  f = Db_Connector("../conf/db_config.ini")

得到结果:

section: ['concurrent', 'baseconf']
options: ['host', 'db_name', 'user', 'password', 'port']
db: [('host', '127.0.0.1'), ('db_name', 'evaluting_sys'), ('user', 'root'), ('password', 'root'), ('port', '3306')]
127.0.0.1 3306 root root

通用模块:支持命令行+import两种形式
ini_op.py

#!/usr/bin/python
# -*- coding:utf-8 -*-
#author: lingyue.wkl
#desc: use to read ini
#---------------------
#2012-02-18 created
#2012-09-02 changed for class support
#---------------------
import sys,os,time
import ConfigParser

class Config:
    def __init__(self, path):
        self.path = path
        self.cf = ConfigParser.ConfigParser()
        self.cf.read(self.path)
    def get(self, field, key):
        result = ""
        try:
            result = self.cf.get(field, key)
        except:
            result = ""
        return result
    def set(self, filed, key, value):
        try:
            self.cf.set(field, key, value)
            cf.write(open(self.path,'w'))
        except:
            return False
        return True
def read_config(config_file_path, field, key): 
    cf = ConfigParser.ConfigParser()
    try:
        cf.read(config_file_path)
        result = cf.get(field, key)
    except:
        sys.exit(1)
    return result
def write_config(config_file_path, field, key, value):
    cf = ConfigParser.ConfigParser()
    try:
        cf.read(config_file_path)
        cf.set(field, key, value)
        cf.write(open(config_file_path,'w'))
    except:
        sys.exit(1)
    return True
if __name__ == "__main__":
   if len(sys.argv) < 4:
      sys.exit(1)
   config_file_path = sys.argv[1] 
   field = sys.argv[2]
   key = sys.argv[3]
   if len(sys.argv) == 4:
      print read_config(config_file_path, field, key)
   else:
      value = sys.argv[4]
      write_config(config_file_path, field, key, value)

第二个示例

import os
import ConfigParser
def main():
    cp = ConfigParser.ConfigParser()    
    cf = open(u"in.ini")
    cp.readfp(cf)
    secs = cp.sections()
    print cp.sections()
    for sec in secs:
        opts = cp.options(sec)
        for opt in opts:
            val = cp.get(sec, opt)
            val += "test....."
            cp.set(sec, opt, val)
    cp.write(open("out.ini", "w"))
if __name__ == '__main__':
    main()
Python 相关文章推荐
Python对小数进行除法运算的正确方法示例
Aug 25 Python
Python深入学习之闭包
Aug 31 Python
Python描述器descriptor详解
Feb 03 Python
Python-嵌套列表list的全面解析
Jun 08 Python
使用python和pygame绘制繁花曲线的方法
Feb 24 Python
PyTorch快速搭建神经网络及其保存提取方法详解
Apr 28 Python
使用Python实现在Windows下安装Django
Oct 17 Python
python多线程高级锁condition简单用法示例
Nov 07 Python
基于Python 中函数的 收集参数 机制
Dec 21 Python
利用PyQt中的QThread类实现多线程
Feb 18 Python
python GUI库图形界面开发之PyQt5布局控件QGridLayout详细使用方法与实例
Mar 06 Python
python多线程实现同时执行两个while循环的操作
May 02 Python
python判断windows隐藏文件的方法
Mar 21 #Python
python解析中国天气网的天气数据
Mar 21 #Python
python实现文件名批量替换和内容替换
Mar 20 #Python
Python读写Redis数据库操作示例
Mar 18 #Python
python实现k均值算法示例(k均值聚类算法)
Mar 16 #Python
python实现保存网页到本地示例
Mar 16 #Python
利用打码兔和超人打码自封装的打码类分享
Mar 16 #Python
You might like
需要发散思维学习PHP
2009/06/29 PHP
火车头discuz6.1 完美采集的php接口文件
2009/09/13 PHP
基于PHP的cURL快速入门教程 (小偷采集程序)
2011/06/02 PHP
ThinkPHP实现事务回滚示例代码
2014/06/23 PHP
PHP中file_exists函数不支持中文名的解决方法
2014/07/26 PHP
php中smarty实现多模版网站的方法
2015/06/11 PHP
PHP children()函数讲解
2019/02/03 PHP
拖动table标题实现改变td的大小(css+js代码)
2013/04/16 Javascript
JS分页控件 可用于无刷新分页
2013/07/23 Javascript
javascript验证上传文件的类型限制必须为某些格式
2013/11/14 Javascript
使用jquery的jsonp如何发起跨域请求及其原理详解
2017/08/17 jQuery
详解require.js配置路径的用法和css的引入
2017/09/06 Javascript
JS实现移动端整屏滑动的实例代码
2017/11/10 Javascript
微信小程序switch组件使用详解
2018/01/31 Javascript
从零开始封装自己的自定义Vue组件
2018/10/09 Javascript
vue element动态渲染、移除表单并添加验证的实现
2019/01/16 Javascript
Vue动态生成el-checkbox点击无法赋值的解决方法
2019/02/21 Javascript
createObjectURL方法实现本地图片预览
2019/09/30 Javascript
vue中使用v-for时为什么不能用index作为key
2020/04/04 Javascript
JS this关键字在ajax中使用出现问题解决方案
2020/07/17 Javascript
[53:52]OG vs EG 2018国际邀请赛淘汰赛BO3 第二场 8.23
2018/08/24 DOTA
python使用PyFetion来发送短信的例子
2014/04/22 Python
《Python之禅》中对于Python编程过程中的一些建议
2015/04/03 Python
Python3 log10()函数简单用法
2019/02/19 Python
Pandas DataFrame数据的更改、插入新增的列和行的方法
2019/06/25 Python
pytorch程序异常后删除占用的显存操作
2020/01/13 Python
python进度条显示-tqmd模块的实现示例
2020/08/23 Python
简单聊聊H5的pushState与replaceState的用法
2018/04/03 HTML / CSS
丝芙兰加拿大官方网站:SEPHORA加拿大
2018/11/20 全球购物
趣味游戏活动方案
2014/02/07 职场文书
2014年环保工作总结
2014/11/26 职场文书
社区母亲节活动总结
2015/02/10 职场文书
个人自荐书范文
2015/03/09 职场文书
大学生读书笔记范文
2015/07/01 职场文书
用golang如何替换某个文件中的字符串
2021/04/25 Golang
4种非常实用的python内置数据结构
2021/04/28 Python