python中ConfigParse模組的用法

2022-03-25 17:38:19 字數 1031 閱讀 4157

configparser 是python自帶的模組, 用來讀寫配置檔案, 用法及其簡單。

配置檔案的格式是:

[...]包含的叫section

section 下有option=value這樣的鍵值

配置檔案config.txt

[section1]

name = hester

age = 28

[section2]

ip = 192.168.1.1

port = 8080

python**

# -* - coding: utf-8 -* -  

import configparser

conf = configparser.configparser()

conf.read("./config.txt")

# 獲取指定的section, 指定的option的值

name = conf.get("section1", "name")

print(name)

age = conf.get("section1", "age")

print age

#獲取所有的section

sections = conf.sections()

print sections

#寫配置檔案

# 更新指定section, option的值

conf.set("section2", "port", "8081")

# 寫入指定section, 增加新option的值

conf.set("section2", "ieport", "80")

# 新增新的 section

# 寫回配置檔案

conf.write(open("./config.txt","w"))

python讀取配置檔案configparser

可讀取寫入配置檔案 import configparser import os import sys class testcfigparser object config configparser.configparser def get value self root dir os.path.di...

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 ...

python 配置檔案讀取configparser

import configparser cp configparser.configparser 例項化 cp.read config.conf encoding utf 8 讀取配置檔案,允許讀取多個配置檔案,用列表 section 裡面的 獲取所有的section f cp.sections p...