Python读属性文件

# coding:utf-8

class Properties:
    def __init__(self, file_name):
        self.file_name = file_name
        self.properties = {}
        try:
            fopen = open(self.file_name, 'r')
            for line in fopen:
                line = line.strip()
                if line.find('=') > 0 and not line.startswith('#'):
                    strs = line.split('=')
                    self.properties[strs[0].strip()] = strs[1].strip()
        except Exception, e:
            raise e
        else:
            fopen.close()

    def has_key(self, key):
        return key in self.properties

    def get(self, key, default_value=''):
        if key in self.properties:
            return self.properties[key]
        return default_value


if __name__ == '__main__':
    p = Properties("E:/a.properties")
    print p.get("name")

  

posted @ 2017-04-30 19:40  413Xiaol  阅读(906)  评论(0编辑  收藏  举报