python教程:ConfigParser模块使用教程
生活随笔
收集整理的這篇文章主要介紹了
python教程:ConfigParser模块使用教程
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.簡介
我們經常需要使用配置文件,例如.conf和.ini等類型,使用ConfigPaser模塊可以對配置文件進行操作。
2.示例
現有配置文件test.ini,其內容如下:
[section_a] a_key1 = str content a_key2 = 10[section_b] b_key1 = b_value1 b_key2 = b_value21讀取配置文件
import ConfigParser import os# 生成config對象 os.chdir('C:\\Study\\python\\configparser') cf = ConfigParser.ConfigParser() # 讀取配置文件 cf.read("test.ini")2讀取數據
# 讀取所有節 sections = cf.sections() print 'sections:', sections結果如下:
結果如下:
結果如下:
結果如下:
3寫入數據
更新指定節和鍵的值
cf.set('section_b', 'b_key1', 'new_value1')結果如下:
[section_a] a_key1 = str content a_key2 = 10[section_b] b_key1 = new_value1 b_key2 = b_value2對指定節,新增鍵
cf.set('section_b', 'b_key3')結果如下:
[section_a] a_key1 = str content a_key2 = 10[section_b] b_key1 = new_value1 b_key2 = b_value2 b_key3 = None對指定節,新增鍵值對
cf.set("section_b", "b_new_key", "b_new_value")結果如下:
''' 學習中遇到問題沒人解答?小編創建了一個Python學習交流QQ群:857662006 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' [section_a] a_key1 = str content a_key2 = 10[section_b] b_key1 = new_value1 b_key2 = b_value2 b_key3 = None b_new_key = b_new_value新增節
cf.add_section('section_c')結果如下:
[section_a] a_key1 = str content a_key2 = 10[section_b] b_key1 = new_value1 b_key2 = b_value2 b_key3 = None b_new_key = b_new_value[section_c]在所有寫入完畢后,進行保存操作:
# 寫入文件 cf.write(open('test.ini', 'w'))總結
以上是生活随笔為你收集整理的python教程:ConfigParser模块使用教程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python教程:深拷贝与浅拷贝的具体区
- 下一篇: python教程:apscheduler