python中cfg是什么?
*.cfg文件一般是程序運行的配置文件,python為讀寫常見配置文件提供了一個ConfigParser模塊,所以在python中解析配置文件相當簡單,下面就舉例說明一下具體的操作方法。
寫文件代碼:
# -* - coding: UTF-8 -* -
import os
import ConfigParser
CONFIG_FILE = "Config.cfg"
host = "127.0.0.1"
port = "5432"
name = "DATABASE_NAME"
username = "postgres"
password = "postgres"
if __name__ == "__main__":
conf = ConfigParser.ConfigParser()
cfgfile = open(CONFIG_FILE,'w')
conf.add_section("DB_Config") # 在配置文件中增加一個段
# 第一個參數是段名,第二個參數是選項名,第三個參數是選項對應的值
conf.set("DB_Config", "DATABASE_HOST", host)
conf.set("DB_Config", "DATABASE_PORT", port)
conf.set("DB_Config", "DATABASE_NAME", name)
conf.set("DB_Config", "DATABASE_USERNAME", username)
conf.set("DB_Config", "DATABASE_PASSWORD", password)
conf.add_section("FL_Config")
# 將conf對象中的數據寫入到文件中
conf.write(cfgfile)
cfgfile.close()
生成的配置文件Config.cfg如下:
[DB_Config]
database_host = 127.0.0.1
database_port = 5432
database_name = DATABASE_NAME
database_username = postgres
database_password = postgres
[FL_Config]
讀文件代碼:
# -* - coding: UTF-8 -* -
import os
import ConfigParser
CONFIG_FILE = "Config.cfg"
def main():
if os.path.exists( os.path.join( os.getcwd(),CONFIG_FILE ) ):
config = ConfigParser.ConfigParser()
config.read(CONFIG_FILE)
#第一個參數指定要讀取的段名,第二個是要讀取的選項名
host = config.get("DB_Config", "DATABASE_HOST")
port = config.get("DB_Config", "DATABASE_PORT")
name = config.get("DB_Config", "DATABASE_NAME")
username = config.get("DB_Config", "DATABASE_USERNAME")
password = config.get("DB_Config", "DATABASE_PASSWORD")
print host, port, name, username, password
if __name__ == '__main__':
main()
輸出結果:127.0.0.1 5432 DATABASE_NAME postgres postgres