Python configuration file: Any file format recommendation? INI format still appropriate? Seems quite old school

前端 未结 8 1724
执念已碎
执念已碎 2020-12-04 10:43

I need to store configurations (key/value) for a Python application and I am searching for the best way to store these configurations in a file.

I run into Python\'s

8条回答
  •  不思量自难忘°
    2020-12-04 11:09

    Dictionaries are pretty popular as well. Basically a hash table.

    {"one": 1, "two": 2} is an example, kind of looks like json.

    Then you can call it up like mydict["one"], which would return 1.

    Then you can use shelve to save the dictionary to a file:

    mydict = shelve.open(filename)
    # then you can call it from there, like
    mydict["one"]
    

    So, it's somewhat easier then an ini file. You can add stuff just like a list or change options pretty easily and then once you close it, it will write it back out.

    Heres a simple example of what i mean:

    import shelve
    
    def main():
        mydict = shelve.open("testfile")
        mydict["newKey"] = value("some comment", 5)
        print(mydict["newKey"].value)
        print(mydict["newKey"].comment)
        mydict.close()
    
    
    class value():
        def __init__(self, comment, value):
            self.comment = comment
            self.value = value
    
    
    
    if __name__ == '__main__':
        main()
    

提交回复
热议问题