Properties file in python (similar to Java Properties)

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

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

propertyName1=propertyValue1
propertyName2=propertyValue2
...
propertyNam         


        
相关标签:
25条回答
  • 2020-11-29 18:45

    i have used this, this library is very useful

    from pyjavaproperties import Properties
    p = Properties()
    p.load(open('test.properties'))
    p.list()
    print(p)
    print(p.items())
    print(p['name3'])
    p['name3'] = 'changed = value'
    
    0 讨论(0)
  • 2020-11-29 18:45

    My Java ini files didn't have section headers and I wanted a dict as a result. So i simply injected an "[ini]" section and let the default config library do its job. The result is converted to a dict:

    from configparser import ConfigParser
    
    @staticmethod
        def readPropertyFile(path):
            # https://stackoverflow.com/questions/3595363/properties-file-in-python-similar-to-java-properties
            config = ConfigParser()
            s_config= open(path, 'r').read()
            s_config="[ini]\n%s" % s_config
            # https://stackoverflow.com/a/36841741/1497139
            config.read_string(s_config)
            items=config.items('ini')
            itemDict={}
            for key,value in items:
                itemDict[key]=value
            return itemDict
    
    0 讨论(0)
  • 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()
    
    0 讨论(0)
  • 2020-11-29 18:46

    This is what I'm doing in my project: I just create another .py file called properties.py which includes all common variables/properties I used in the project, and in any file need to refer to these variables, put

    from properties import *(or anything you need)
    

    Used this method to keep svn peace when I was changing dev locations frequently and some common variables were quite relative to local environment. Works fine for me but not sure this method would be suggested for formal dev environment etc.

    0 讨论(0)
  • 2020-11-29 18:47

    I was able to get this to work with ConfigParser, no one showed any examples on how to do this, so here is a simple python reader of a property file and example of the property file. Note that the extension is still .properties, but I had to add a section header similar to what you see in .ini files... a bit of a bastardization, but it works.

    The python file: PythonPropertyReader.py

    #!/usr/bin/python    
    import ConfigParser
    config = ConfigParser.RawConfigParser()
    config.read('ConfigFile.properties')
    
    print config.get('DatabaseSection', 'database.dbname');
    

    The property file: ConfigFile.properties

    [DatabaseSection]
    database.dbname=unitTest
    database.user=root
    database.password=
    

    For more functionality, read: https://docs.python.org/2/library/configparser.html

    0 讨论(0)
  • 2020-11-29 18:47

    This is what i had written to parse file and set it as env variables which skips comments and non key value lines added switches to specify hg:d

    • -h or --help print usage summary
    • -c Specify char that identifies comment
    • -s Separator between key and value in prop file
    • and specify properties file that needs to be parsed eg : python EnvParamSet.py -c # -s = env.properties

      import pipes
      import sys , getopt
      import os.path
      
      class Parsing :
      
              def __init__(self , seprator , commentChar , propFile):
              self.seprator = seprator
              self.commentChar = commentChar
              self.propFile  = propFile
      
          def  parseProp(self):
              prop = open(self.propFile,'rU')
              for line in prop :
                  if line.startswith(self.commentChar)==False and  line.find(self.seprator) != -1  :
                      keyValue = line.split(self.seprator)
                      key =  keyValue[0].strip() 
                      value = keyValue[1].strip() 
                              print("export  %s=%s" % (str (key),pipes.quote(str(value))))
      
      
      
      
      class EnvParamSet:
      
          def main (argv):
      
              seprator = '='
              comment =  '#'
      
              if len(argv)  is 0:
                  print "Please Specify properties file to be parsed "
                  sys.exit()
              propFile=argv[-1] 
      
      
              try :
                  opts, args = getopt.getopt(argv, "hs:c:f:", ["help", "seprator=","comment=", "file="])
              except getopt.GetoptError,e:
                  print str(e)
                  print " possible  arguments  -s <key value sperator > -c < comment char >    <file> \n  Try -h or --help "
                  sys.exit(2)
      
      
              if os.path.isfile(args[0])==False:
                  print "File doesnt exist "
                  sys.exit()
      
      
              for opt , arg  in opts :
                  if opt in ("-h" , "--help"):
                      print " hg:d  \n -h or --help print usage summary \n -c Specify char that idetifes comment  \n -s Sperator between key and value in prop file \n  specify file  "
                      sys.exit()
                  elif opt in ("-s" , "--seprator"):
                      seprator = arg 
                  elif opt in ("-c"  , "--comment"):
                      comment  = arg
      
              p = Parsing( seprator, comment , propFile)
              p.parseProp()
      
          if __name__ == "__main__":
                  main(sys.argv[1:])
      
    0 讨论(0)
提交回复
热议问题