python3使用configparser读取带有中文的配置文件出现UnicodeDecodeError错误

来源:互联网 发布:中邮网络培训学院 编辑:程序博客网 时间:2024/05/01 15:51

问题:
使用configparser读取配置文件时,出现UnicodeDecodeError错误,在没有任何中文的时候读取可以的,加了1句中文注释后就抛出异常,异常如下:

这里写图片描述

def readconfig(filename):    cf = configparser.ConfigParser()    try:        configcontent = []        cf.read(filename)        sections = cf.sections()        for s in sections:            configcontent.append(cf.items(s))    except:        print("throw a exception:\n{e}".format(e=sys.exc_info()))        return None    else:        return configcontent

配置文件如下:

# -*- coding: utf-8 -*-# 配置文件键值对中如果要表示%,请用"%%"代替"%"[http://meeting.sciencenet.cn]way = getbase_url = "http://meeting.sciencenet.cn/index.php?s=%%2FCategory%%2Findex&cid=5&p="begin = 1end = 10tableSelector = #meetinglist_left > div:nth-child(2) > div.content680 > table:nth-child(1)row = trrowSelector = tr:gt(1)column = tdhref = 1cnName = 1enName = nulltag = nulllocation = 3sponsor = nullstartDate = 5

解决方法
这里写图片描述

注意
对于有BOM(如Windows下用记事本指定为utf-8)的文件,需要使用 utf-8-sig,即把encoding=utf-8 改为 encoding= utf-8-sig

参考链接:
http://www.07net01.com/2015/03/780710.html

阅读全文
0 0
原创粉丝点击