標籤:display fir class otto splay 不能 img tabs 列印
configparse模組常用於產生和修改常見的配置文檔
組建組態模組:用字典寫
import configparserconfig = configparser.ConfigParser()config["DEFAULT"] = {‘ServerAliveInterval‘: ‘45‘, ‘Compression‘: ‘yes‘, ‘CompressionLevel‘: ‘9‘}config[‘USER‘] = {}config[‘USER‘][‘User‘] = ‘hhh‘config[‘SSH‘] = {}topsecret = config[‘SSH‘]topsecret[‘Host Port‘] = ‘50022‘ # mutates the parsertopsecret[‘ForwardX11‘] = ‘no‘ # same hereconfig[‘DEFAULT‘][‘ForwardX11‘] = ‘yes‘with open(‘example.ini‘, ‘w‘) as configfile: config.write(configfile)
讀取配置:config.sections()
import configparserconfig = configparser.ConfigParser()config.read(‘example.ini‘) print(config.sections()) # [‘USER‘, ‘SSH‘], 預設不dayin[DEFAULT]模組print(config[‘USER‘]) # <Section: USER>print(config[‘USER‘][‘user‘]) # hgprint(config.defaults()) # 列印預設模組, 列印出來一個有序的字典print(config.has_section(‘USER‘)) # True OrderedDictprint(config[‘DEFAULT‘][‘compressionlevel‘]) # 9 # 列印預設模組, 列印出來一個有序的字典OrderedDict# 跟字典一樣,只列印key的資訊for key in config[‘DEFAULT‘]: # print(key, v) 報錯, too many values to unpack (expected 2) print(key)
刪除整個模組: remove,檔案不能修改,只能覆蓋,可以重新寫入新的檔案
import configparserconfig = configparser.ConfigParser()config.read(‘example.ini‘)# 檔案不能修改,只能覆蓋,可以重新寫入新的檔案config.remove_section(‘SSH‘)with open(‘example.ini‘, ‘w‘, encoding=‘utf-8‘) as f: config.write(f)print(config.sections())
刪除模組下的某個元素
import configparserconfig = configparser.ConfigParser()config.read(‘example.ini‘)print(config.has_option(‘USER‘, ‘user‘))config.remove_option(‘USER‘, ‘user‘)print(config.has_option(‘USER‘, ‘user‘))with open(‘example.ini‘, ‘w‘, encoding=‘utf-8‘) as f: config.write(f)
修改配置:
import configparserconfig = configparser.ConfigParser()config.read(‘example.ini‘)print(config[‘USER‘][‘user‘])config.set(‘USER‘, ‘user‘, ‘ftl‘)print(config[‘USER‘][‘user‘])with open(‘example.ini‘, ‘w‘, encoding=‘utf-8‘) as f: config.write(f)
Python學習---重點模組之configparse