正文
从windows拷贝到linux的属性文件,编码会有点不一样,linux是utf-8 ,windows是utf-8 bom,以下方法对不同文件编码进行兼容。同时,如果没有section,自动添加section [default]
import configparser
import chardet
def getFileEncoding(filePath_str):
data = open(filePath_str, "rb").read()
encoding_json = chardet.detect(data)
encoding_str = encoding_json.get("encoding")
return encoding_str
def getLocalConfig(file_path):
cf = configparser.ConfigParser()
try:
if os.path.exists(file_path):
encoding_str = getFileEncoding(file_path)
with open(file_path, encoding=encoding_str) as f:
file_content = f.read()
if not file_content.startswith('[default]\n'):
file_content = '[default]\n' + file_content
else:
file_content = '[default]\n'
cf.read_string(file_content)