讀取配置檔案
# coding:utf-8
import configparser
# import os
defcfg()
: conf = configparser.configparser(
) conf.read(
"config.ini"
)print
(conf.sections())
# 讀取配置檔案裡所有的section
print
(conf.options(
"test1"))
# 列印出test1這個section下包含key
print
(conf.get(
"test1"
,"ip"))
# 列印出test1這個section下包含key值
print
(conf.items(
"cmd"))
# 列印test1這個section下所有的key及對應的values
if"add"
notin
"add"
: conf.add_section(
"add"
)# 新增section到配置檔案
conf.
set(
"add"
,"ip"
,"11.11.1.1"
)# add section新增ip引數和值
conf.
set(
"add"
,"addr"
,"shenzhen"
) conf.write(
open
("config.ini"
,"w"))
# 寫完資料要write一下
else
: conf.
set(
"add"
,"ip"
,"11.11.1.2"
)# add section新增ip引數和值
conf.
set(
"add"
,"addr"
,"shen zhen etekcity"
) conf.write(
open
("config.ini"
,"w"))
# 寫完資料要write一下
print
(conf.items(
"add"))
# 列印剛新增的新內容
if __name__ ==
'__main__'
: cfg(
)
python學習 常用操作 if語句
if語句 與,同時成立執行下乙個 或,滿足乙個就執行 非,執行 coding utf 8 a 1 b 2 c 5 defexample1 與 and if a b and b c 2個比較同時成立才會執行下一步列印 print a小於b,b小於c def example2 或 or if a b o...
python檔案讀取操作
r 讀模式 w 寫模式 a 追加模式 b 二進位制模式 可新增到其他模式中使用 讀或者寫模式 可新增到其他模式中使用 read 方法 一次讀取檔案所有內容。a.txt檔案內容如下 hello,world 例項 f open a.txt r a f.read f.close print a 輸出 he...
Python讀取檔案常用的幾種簡單小操作
1.普通讀取f open 開啟檔案,迴圈讀取 def read filename f open filename,r for line in f print line 2.with上下文讀取def read filename with open filename,r as f for line in...