7月 03

在linux下用python读取其他操作系统编写的配置文件

  在windows、mac、linux下编写的配置文件会有头部或者换行有区别。为了分析方便简单做个记录,只为演示,代码并不完整,需要自己修改

def conf(conf_context):
    # 替换window或mac操作系统下的换行符
    import re
    _get_file = re.sub(r'(\r\n|\r|\n)', '\n', conf_context)
    # 将配置放在内存中
    import StringIO
    _tmp_file = StringIO.StringIO()
    # 将文件写入内存
    _tmp_file.write(_get_file)
    _tmp_file.seek(0)
    # 如果是在window下编辑的文件将,utf-8 BOM开始的头替换掉
    if _tmp_file.read(3).startswith('\xef\xbb\xbf'):
        _tmp_file.seek(3)
    else:
        _tmp_file.seek(0)
    # 导入配置
    import ConfigParser
    try:
        cf = ConfigParser.SafeConfigParser()
        cf.readfp(_tmp_file)
        config_list = cf.sections()
    except:
        _tmp_file.close()
        return "error"
    _tmp_file.close()
    return "ok"