ConfigParser模塊用於生成和修改常見配置文檔
文件格式:
[DEFAULT] ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 ForwardX11 = yes [bitbucket.org] User = hg [topsecret.server.com] Port = 50022 ForwardX11 = no
生成:
import configparser config = configparser.ConfigParser() config["DEFAULT"] = {'ServerAliveInterval': '45', # 直接生成DEFAULT 'Compression': 'yes', 'CompressionLevel': '9'} config['bitbucket.org'] = {} # 生成空的bitbucket.org config['bitbucket.org']['User'] = 'hg' # 再賦值 config['topsecret.server.com'] = {} # 生成空的topsecret.server.com topsecret = config['topsecret.server.com'] # 再賦值 topsecret['Host Port'] = '50022' # mutates the parser topsecret['ForwardX11'] = 'no' # same here config['DEFAULT']['ForwardX11'] = 'yes' # 給DEFAULT添加新內容 with open('example.ini', 'w') as configfile: # 打開文件並寫入 config.write(configfile)
讀取:
import configparser config = configparser.ConfigParser() print(config.sections()) # 開始時為空 config.read('example.ini') # 讀取文件 print(config.sections()) # 不打印DEFAULT print('\n') print('bitbucket.org' in config) # 查找bitbucket.org是否存在 print('bytebong.com' in config) print('\n') print(config['bitbucket.org']['User']) # 讀取bitbucket.org下的User print(config['DEFAULT']['Compression']) print('\n') topsecret = config['topsecret.server.com'] print(topsecret['ForwardX11']) # 讀取topsecret.server.com下的ForwardX11 print(topsecret['host port']) print('\n') for key in config['bitbucket.org']: # 讀取bitbucket.org下所有的key(包括DEFAULT下的) print(key) print('\n') print(config['bitbucket.org']['ForwardX11']) # bitbucket.org下沒有ForwardX11,就默認為DEFAULT下的
輸出結果:
[]
['bitbucket.org', 'topsecret.server.com']
True
False
hg
yes
no
50022
user
serveraliveinterval
compressionlevel
compression
forwardx11
yes
增刪改查:
import configparser config = configparser.ConfigParser() config.read('example.ini') sec = config.remove_section('bitbucket.org') # 刪除 config.remove_option('topsecret.server.com', 'host port') config.write(open('new.ini', "w")) sec = config.has_section('topsecret.server.com') # 判斷是否存在 print(sec) sec = config.add_section('bytebong.com') # 添加 config.write(open('new.ini', "w")) config.set('bytebong.com', 'host port', '1111') # 修改 config.write(open('new.ini', "w"))
輸出結果:
True