python讀寫配置檔案操作
阿新 • • 發佈:2018-12-20
1.簡介
- read(filename) 讀取ini檔案內容
- sections() 以列表形式展示所有的section
- options(section) 展示該section的option
- items(section) 得到該section的所有鍵值對
- get(section,option) 得到section中option的值,返回為string型別
- getint(section,option) 得到section中option的值,返回int型別,還有相應的getboolean()和getfloat()函式。
2.動態寫入配置檔案
- add_section(section) 新增一個新的section
- set(section,option,value) 新增section中的option
def writeIni(): # 第一步:建立conf物件 conf = configparser.ConfigParser() # 第二步:新增section、options的值 conf.add_section("path") conf.set("path", "back_dir", "/Users/abc/PycharmProjects/Pythoncoding/projects/") # option conf.set("path", "target_dir", "/Users/abc/PycharmProjects/Pythoncoding/") # option conf.add_section("file") conf.set("file", "back_file", "apitest") conf.set("file", "num", "10") # 第三步:寫入檔案 with open("path.ini", 'w')as conffile: conf.write(conffile)
執行以上程式碼,寫入配置檔案,生成一個path.ini配置檔案:
[path]
back_dir = /Users/abc/PycharmProjects/Pythoncoding/projects/
target_dir = /Users/abc/PycharmProjects/Pythoncoding/
[file]
back_file = apitest
num = 10
讀取配置檔案:
def readIni(): config = configparser.ConfigParser() # 第四步:讀取配置檔案中的section、options的值 # config.read_file(open('path.ini')) # 一開始是用上面的read_file讀取配置檔案的,但是配置檔案裡有中文 # 讀取了之後出現編碼問題,執行出錯,故用下面的read函式讀取 config.read('path.ini', encoding='UTF-8') back_dir = config.get('path', 'back_dir') back_file = config.get("file", "back_file") num = config.get("file", "num") target_dir = config.get("path", "target_dir") l1 = config.sections() print("back_dir = %s" % back_dir) print("back_file = %s" % back_file) print("num = %s" % num) print("target_dir = %s" % target_dir) print("l1 = %s" % l1) i = config.getint("file", "num") print("i = %s" % i) l2 = config.options("file") print("l2 = %s" % l2) l3 = config.items("file") print("l3 = %s" % l3) """ 輸出如下: back_dir = /Users/abc/PycharmProjects/Pythoncoding/projects/ back_file = apitest num = 10 target_dir = /Users/abc/PycharmProjects/Pythoncoding/ l1 = ['path', 'file'] i = 10 l2 = ['back_file', 'num'] l3 = [('back_file', 'apitest'), ('num', '10')] """
刪除section和option操作操作:
def remove_section():
conf_path = "path.ini"
config = configparser.ConfigParser()
config.read(conf_path, encoding='UTF-8')
# 刪除section是section1裡md5選項
config.remove_option('section1', 'md5')
# 刪除section是section2裡所有選項
config.remove_section('section2')
# 刪除後必須寫入檔案才有效
with open(conf_path, 'w', encoding="UTF-8")as file:
config.write(file)