一、建立配置檔案
在d盤建立乙個配置檔案,名字為:test.ini
內容如下:
[baseconf]
host=127.0.0.1
port=3306
user=root
password=root
db_name=gloryroad
[test]
ip=127.0.0.1
int=1
float=1.5
bool=true
注意:要將檔案儲存為ansi編碼,utf-8編碼會報錯
檔案中的[baseconf]為section
二、讀配置檔案
import configparser cf=configparser.configparser() cf.read(path) 讀配置檔案(ini、conf)返回結果是列表 cf.sections() 獲取讀到的所有sections(域),返回列表型別 cf.options('sectionname') 某個域下的所有key,返回列表型別 cf.items('sectionname') 某個域下的所有key,value對 value=cf.get('sectionname','key') 獲取某個yu下的key對應的value值 cf.type(value) 獲取的value值的型別(1)getint(section, option)
獲取section中option的值,返回int型別資料,所以該函式只能讀取int型別的值。
(2)getboolean(section, option)
獲取section中option的值,返回布林型別資料,所以該函式只能讀取boolean型別的值。
(3)getfloat(section, option)
獲取section中option的值,返回浮點型別資料,所以該函式只能讀取浮點型別的值。
(4)has_option(section, option)
檢測指定section下是否存在指定的option,如果存在返回true,否則返回false。
(5)has_section(section)
檢測配置檔案中是否存在指定的section,如果存在返回true,否則返回false。
三、動態寫配置檔案
cf.add_section('test') 新增乙個域 cf.set('test3','key12','value12') 域下新增乙個key value對 cf.write(open(path,'w')) 要使用'w' learn to fail, failure to learn內容擴充套件:
python使用配置檔案過程
通過配置檔案將變數暴露給使用者修改
標準庫模組configparser,從而可在配置檔案中使用標準格式。
必須使用[files]、[colors]等標題將配置檔案分成幾部分(section)。標題的名稱可隨便指定,但必須將它們用方括號括起。
$ cat area.ini
[numbers]
pi: 3.1415926535893971
[messages]
greeting: welcome to the area calutation program!
question: plse enter the radius
result_message: the area is
使用python 讀取他
from configparser import configparser
configfile = "area.ini"
config = configparser()
#讀取配置檔案
config.read(configfile)
print(config['messages'].get('greeting'))
radius = float(input(config['messages'].get('question') + ' '))
# 以空格結束以便接著在當前行列印:
print(config['messages'].get('result_message'),end=' ')
print(config['numbers'].getfloat('pi') * radius**2)
python函式如何寫 python如何寫函式
python函式的定義 定義函式,也就是建立乙個函式,可以理解為建立乙個具有某些用途的工具。定義函式需要用 def 關鍵字實現,具體的語法格式如下 def 函式名 形參列表 由零條到多條可執行語句組成的 塊 return 返回值 其中,用 括起來的為可選擇部分,即可以使用,也可以省略。此格式中,各部...
python如何寫日誌 python如何寫日誌
這篇文章介紹了 python 的 logging 模組,包括它的設計以及針對更多複雜案例的適用方法。這篇文章不是寫給開發者的文件,它更像是乙個指導手冊,來說明 python 的 logging 模板是如何搭建的,並且激發感興趣的人深入研究。為什麼使用 logging 模組?也許會有開發者會問,為什麼...
如何寫 makefile檔案
如何寫 makefile檔案 學習別人的程式就面臨著重寫makefile的問題.下面以問答的形式來解釋如何寫makefile檔案.1.makefile的核心 target.目標檔案 object檔案 可執行檔案 標籤 prerequisites 生成target所需要的檔案,也可以是target中的...