如何寫python的配置文件
一、創建配置文件
在D盤建立一個配置文件,名字為:test.ini
內容如下:
[baseconf]host=127.0.0.1port=3306user=rootpassword=rootdb_name=gloryroad[test]ip=127.0.0.1int=1float=1.5bool=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 radiusresult_message: The area is
使用python 讀取他
from configparser import ConfigParserCONFIGFILE = '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寫配置文件方法內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
1. IDEA EasyCode 一鍵幫你生成所需代碼2. Ajax引擎 ajax請求步驟詳細代碼3. Java構建JDBC應用程序的實例操作4. Spring應用拋出NoUniqueBeanDefinitionException異常的解決方案5. ThinkPHP5 通過ajax插入圖片并實時顯示(完整代碼)6. javascript設計模式 ? 建造者模式原理與應用實例分析7. 一篇文章帶你了解JavaScript-對象8. Python使用oslo.vmware管理ESXI虛擬機的示例參考9. IntelliJ IDEA設置條件斷點的方法步驟10. Express 框架中使用 EJS 模板引擎并結合 silly-datetime 庫進行日期格式化的實現方法
