Properties file in python (similar to Java Properties)

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

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

propertyName1=propertyValue1
propertyName2=propertyValue2
...
propertyNam         


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

    You can use the following function, which is the modified code of @mvallebr. It respects the properties file comments, ignores empty new lines, and allows retrieving a single key value.

    def getProperties(propertiesFile ="/home/memin/.config/customMemin/conf.properties", key=''):
        """
        Reads a .properties file and returns the key value pairs as dictionary.
        if key value is specified, then it will return its value alone.
        """
        with open(propertiesFile) as f:
            l = [line.strip().split("=") for line in f.readlines() if not line.startswith('#') and line.strip()]
            d = {key.strip(): value.strip() for key, value in l}
    
            if key:
                return d[key]
            else:
                return d
    
    0 讨论(0)
  • 2020-11-29 18:36

    This is not exactly properties but Python does have a nice library for parsing configuration files. Also see this recipe: A python replacement for java.util.Properties.

    0 讨论(0)
  • 2020-11-29 18:38
    import json
    f=open('test.json')
    x=json.load(f)
    f.close()
    print(x)
    

    Contents of test.json: {"host": "127.0.0.1", "user": "jms"}

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

    if you don't have multi line properties and a very simple need, a few lines of code can solve it for you:

    File t.properties:

    a=b
    c=d
    e=f
    

    Python code:

    with open("t.properties") as f:
        l = [line.split("=") for line in f.readlines()]
        d = {key.strip(): value.strip() for key, value in l}
    
    0 讨论(0)
  • 2020-11-29 18:41

    A java properties file is often valid python code as well. You could rename your myconfig.properties file to myconfig.py. Then just import your file, like this

    import myconfig
    

    and access the properties directly

    print myconfig.propertyName1
    
    0 讨论(0)
  • 2020-11-29 18:44

    you can use parameter "fromfile_prefix_chars" with argparse to read from config file as below---

    temp.py

    parser = argparse.ArgumentParser(fromfile_prefix_chars='#')
    parser.add_argument('--a')
    parser.add_argument('--b')
    args = parser.parse_args()
    print(args.a)
    print(args.b)
    

    config file

    --a
    hello
    --b
    hello dear
    

    Run command

    python temp.py "#config"
    
    0 讨论(0)
提交回复
热议问题