Python怎樣去讀寫配置檔案

2021-08-18 17:57:43 字數 2018 閱讀 5794

用configparser模組。

首先準備乙個配置檔案,如:example

[oppo]

platformname = android

platformversion = 6.0

devicename = 2a22cee

.sina

.weibo

url =

.0.1:4723/wd/hub

[book]

title:consadfadfas

time:

2018/04/13

[size]

size:

1024

[other]

blog:csdn.net

在這個模組兒中,section代表中括號裡的內容。option代表每個分類下的key

in [1]: import configparser

in [2]: config=configparser.configparser() ##建立乙個例項

in [3]: config.read('example') ##讀取配置檔案

out[3]: ['example']

in [5]: config.get('book','title') ##查詢book下的title對應的值

out[5]: 'consadfadfas'

in [9]: print "by",config.get('book','time') ##查詢book下time對應的值

by 2018/04/13

in [10]: config.sections() ##查詢所有的section

out[10]: ['oppo', 'book', 'size', 'other']

in [11]: for section in config.sections(): ##寫乙個for迴圈,列印出所有的內容

...: print section

...: for option in config.options(section):

...: print " ",option,"=",config.get(section,option)

...:

oppo

platformname = android

platformversion = 6.0

devicename = 2a22cee

url =

.0.1:4723/wd/hub

book

title = consadfadfas

time = 2018/04/13

size

size = 1024

other

blog = csdn.net

in [13]: config.options('oppo') ##查詢oppo下的所有option

out[13]:

['platformname',

'platformversion',

'devicename',

'url']

in [14]: config.add_section("like") ##新增乙個section叫做like

in [15]: config.sections() ##查詢所有的section

out[15]: ['oppo', 'book', 'size', 'other', 'like']

in [16]: config.set('like','food','meat') ##給名為like的section新增option以及對應的value

in [17]: config.set('like','drink','orange') ##同上

in [25]: config.write(open('example','r+')) ##將所有改變寫入檔案中

python讀寫配置檔案

本文主要介紹在python中讀寫配置檔案。python主要使用configparser模組來進行配置檔案的操作。import configparser 讀操作 conf configparser.configparser conf.read config.ini 檔名 讀取指定的section和na...

Python之配置檔案讀寫

configparser模組 一 建立配置檔案 在d盤建立乙個配置檔案,名字為 test.ini 內容如下 baseconf host 127.0.0.1 port 3306 user root password root db name gloryroad test ip 127.0.0.1 in...

python配置檔案讀寫(ConfigParse)

ini檔案格式 section0 key0 value0 key1 value1 section1 key2 value2 key3 value示例 config num 40column 8create size x 400create size y 300 color 深藍 dark blue ...