Properties file in python (similar to Java Properties)

后端 未结 25 2864
故里飘歌
故里飘歌 2020-11-29 17:41

Given the following format (.properties or .ini):

propertyName1=propertyValue1
propertyName2=propertyValue2
...
propertyNam         


        
25条回答
  •  感情败类
    2020-11-29 18:46

    You can use a file-like object in ConfigParser.RawConfigParser.readfp defined here -> https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.readfp

    Define a class that overrides readline that adds a section name before the actual contents of your properties file.

    I've packaged it into the class that returns a dict of all the properties defined.

    import ConfigParser
    
    class PropertiesReader(object):
    
        def __init__(self, properties_file_name):
            self.name = properties_file_name
            self.main_section = 'main'
    
            # Add dummy section on top
            self.lines = [ '[%s]\n' % self.main_section ]
    
            with open(properties_file_name) as f:
                self.lines.extend(f.readlines())
    
            # This makes sure that iterator in readfp stops
            self.lines.append('')
    
        def readline(self):
            return self.lines.pop(0)
    
        def read_properties(self):
            config = ConfigParser.RawConfigParser()
    
            # Without next line the property names will be lowercased
            config.optionxform = str
    
            config.readfp(self)
            return dict(config.items(self.main_section))
    
    if __name__ == '__main__':
        print PropertiesReader('/path/to/file.properties').read_properties()
    

提交回复
热议问题