Python读写配置文件

创建配置文件

import configparser

def createConfig(path):
    config=configparser.ConfigParser()
    config.add_section("Settings")
    config.set("Settings","font","Consoles")
    config.set("Settings","font_size","10")
    config.set("Settings", "font_style", "Normal")
    with open(path,"w") as config_file:
        config.write(config_file)
        
if __name__ == '__main__':
    path="settings.ini"
    createConfig(path)
    
# setting.ini文件内容为
# [Settings]
# font = Consoles
# font_size = 10
# font_style = Normal

读取、更新、删除配置文件中的选项

import configparser
import os

def crudConfig(path):
    if not os.path.exists(path):
        createConfig(path)
    config=configparser.ConfigParser()
    config.read(path)

    # read
    font=config.get("Settings","font")
    font_size=config.get("Settings","font_size")
    print(font)
    print(font_size)

    # update
    config.set("Settings","font_size","12")

    # delete
    config.remove_option("Settings","font_style")

    with open(path,"w") as config_file:
        config.write(config_file)
        
if __name__ == '__main__':
    path="settings.ini"
    crudConfig(path)

你可能感兴趣的:(Python,Python,读,写,配置文件,configparser)