【背景】python
Windows 的記事本會給 UTF-8 文件添加 BOM 頭,很煩,搞個通用的讀取配置文件的代碼。可能報這種錯誤:
bash
configparser.MissingSectionHeaderError: File contains no section headers.ide
file: 'D:\\Python3Project\\ClearWFWatermark\\config\\config.ini', line: 1spa
'\ufeff[config]\n'code
【config.ini】orm
[config] SrcRoot=D:\input DstRoot=D:\output
【t.py】blog
#encoding=utf-8 #author: walker #date: 2018-03-31 #summary: 讀取 UTF-8/UTF-8-BOM 配置文件 import os, sys from configparser import ConfigParser SrcRoot = r'' DstRoot = r'' #讀取配置文件 def ReadConfig(): global SrcRoot, DstRoot cfg = ConfigParser() # cfg.optionxform = str # 保持鍵的大小寫 cfgFile = 'config.ini' if not os.path.exists(cfgFile): input(cfgFile + ' not found') sys.exit(-1) with open(cfgFile, mode='rb') as f: content = f.read() if content.startswith(b'\xef\xbb\xbf'): # 去掉 utf8 bom 頭 content = content[3:] cfg.read_string(content.decode('utf8')) if not cfg.sections(): input('Read config.ini failed...') sys.exit(-1) SrcRoot = cfg.get('config', 'SrcRoot').strip() if not os.path.exists(SrcRoot): print('Error: not exists %s' % SrcRoot) sys.exit(-1) print('SrcRoot: %s' % SrcRoot) DstRoot = cfg.get('config', 'DstRoot').strip() if not os.path.exists(DstRoot): print('Error: not exists %s' % DstRoot) sys.exit(-1) print('DstRoot: %s' % DstRoot) print('Read config.ini successed!') if __name__ == '__main__': ReadConfig()
【cmd】ip
λ python3 t.py SrcRoot: D:\input DstRoot: D:\output Read config.ini successed!
【讀取配置文件,並轉換爲二級有序字典】utf-8
# encoding: utf-8 # author: walker # date: 2018-06-01 # summary: 讀取配置文件,並轉換爲二級有序字典,結果其實相似於私有變量 cfg._sections import os, sys from collections import OrderedDict from configparser import ConfigParser from pprint import pprint # 讀取配置文件 # 返回一個二級字典 def ReadConfig(): cfg = ConfigParser() cfg.optionxform = str # 保持鍵的大小寫 cfgFile = 'config.ini' if not os.path.exists(cfgFile): input(cfgFile + ' not found') sys.exit(-1) with open(cfgFile, mode='rb') as f: content = f.read() if content.startswith(b'\xef\xbb\xbf'): # 去掉 utf8 bom 頭 content = content[3:] cfg.read_string(content.decode('utf8')) if not cfg.sections(): input('Read config.ini failed...') sys.exit(-1) dic = OrderedDict() for section in cfg.sections(): dic[section] = OrderedDict() for option in cfg.options(section): dic[section][option] = cfg.get(section, option).strip() #pprint(dic) print('Read %s completed!' % cfgFile) return dic
*** walker ***get