zoukankan      html  css  js  c++  java
  • python的ConfigParser读取设置配置文件

    python 读写配置文件在实际应用中具有十分强大的功能,在实际的操作中也有相当简捷的操作方案,以下的文章就是对python 读写配置文件的具体方案的介绍,望你浏览完下面的文章会有所收获。

    python 读写配置文件ConfigParser模块是python自带的读取配置文件的模块.通过他可以方便的读取配置文件. 这篇文章简单介绍一下python 读写配置文件的方法.

    配置文件.顾名思议就是存放配置的文件.下面是个例子

    点击(此处)折叠或打开

    1. [info] 
    2. age = 21
    3. name = chen
    4. gender = male

    其中[ ] 中的info是这段配置的名字下面age,name都是属性下面的代码演示了如何读取python 读写配置文件.和修改配置中变量的值

    点击(此处)折叠或打开

    1. from __future__ import with_statement 
    2. import ConfigParser 
    3. config=ConfigParser.ConfigParser() 
    4. with open(''testcfg.cfg'',''rw'') as cfgfile: 
    5. config.readfp(cfgfile) 
    6. name=config.get(''info'',''name'') 
    7. age=config.get(''info'',''age'') 
    8. print name 
    9. print age 
    10. config.set(''info'',''gender'',''male'') 
    11. config.set(''info'',''age'',''21'') 
    12. age=config.get(''info'',''age'') 
    13. print name 
    14. print age

    首先

    config=ConfigParser.ConfigParser() 

    得到一个配置config对象.下面打开一个配置文件 cfgfile. 用readfp()读取这个文件.这样配置的内容就读到config对象里面了.接下来一个问题是如何读取值.常用的方法是get() 和getint() . get()返回文本. getint()返回整数

    name=config.get(''info'',''name'')  

    意思就是.读取config中info段中的name变量值.最后讲讲如何设置值.使用set(段名,变量名,值) 来设置变量.config.set(''info'',''age'',''21'') 表示把info段中age变量设置为21. 就这么简单. 以上就是对python 读写配置文件

  • 相关阅读:
    DRF 版本和认证
    DRF 视图和路由
    DRF 序列化组件
    RESTful
    Vuex以及axios
    npm、webpack、vue-cli
    Vue 生命周期
    Vue Router
    Vue 组件
    Vue 快速入门
  • 原文地址:https://www.cnblogs.com/fkissx/p/5832727.html
Copyright © 2011-2022 走看看