項目中遇到要讀取配置的情況, 所有就用了 ConfigParser 模塊, 乍一看沒有啥問題, 但是測試過程中發(fā)現(xiàn)還是有坑.
在windows版的程序中, 客戶配置ini文件一般都是用記事本修改, 但是本身記事本會強制加上一個BOM頭, 然后ConfigParser在read時候救護拋錯, 嘗試了一些方法, 最終用指定read的編碼方式的方法解決, 這里貼一下.
configparser.ConfigParser().read(config_file_path, encoding="utf-8-sig")
當(dāng)然還有別的方法:
fp = open("file.txt")
s = fp.read()
u = s.decode("utf-8-sig")
# That gives you a unicode string without the BOM. You can then use
s = u.encode("utf-8")
本質(zhì)差不多.
Reference: