Sunday, February 19, 2017

记录ConfigParser在Python2.6下一坑

import ConfigParser
import codecs
import os

#category_cfg_file="category.cfg"

category_cfg = ConfigParser.ConfigParser()
with codecs.open('feature_common.config', 'r',encoding='utf-8') as configfile:
    category_cfg.readfp(configfile)
   
   
features = category_cfg.sections()


上面代码在Python2.7下,返回的features顺序和配置文件中的顺序是一样的,可是服务器用的是Python2.7,这个返回的竟然是无序的,查到了很久才查到这一块。我草快被坑死了。

http://stackoverflow.com/questions/1134071/keep-configparser-output-files-sorted
找到答案,修复方法如下

In Python 2.7, you can from collections import OrderedDict and use ConfigParser(dict_type=OrderedDict) to make the parser use an ordered dictionary. Based on a minimal amount of testing, I think this should serve you well.

No comments:

Post a Comment