首页 > 编程语言 > 详细

Python3 读取配置文件(UTF-8/UTF-8-BOM)

时间:2018-03-31 10:51:58      阅读:274      评论:0      收藏:0      [点我收藏+]
【背景】

  Windows 的记事本会给 UTF-8 文件添加 BOM 头,很烦,搞个通用的读取配置文件的代码。


【config.ini】

[config]
SrcRoot=D:\input
DstRoot=D:\output


【t.py】

#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()
	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:]
	cfgLst = cfg.read(cfgFile, encoding='utf-8-sig')
	if len(cfgLst) < 1:
		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】

λ python3 t.py
SrcRoot: D:\input
DstRoot: D:\output
Read config.ini successed!


*** walker ***


Python3 读取配置文件(UTF-8/UTF-8-BOM)

原文:http://blog.51cto.com/walkerqt/2093263

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!