Python config文件读写:ConfigParser

2018年9月1日 3977点热度 3人点赞 0条评论

坑都在下面注释里了:

先来个示例文件,db是section,每个section有无数的key-value对

[db]
server="127.0.0.1"
user="root"
password="root"

下面是代码:

def getConfig(section, key):
    config = ConfigParser.ConfigParser()
    path = os.path.split(os.path.realpath(__file__))[0] + '/db.conf'   #这是文件的路径
    config.read(path)
    return config.get(section, key)    #这个没什么问题

def setConfig(section, key,value):
    config = ConfigParser.ConfigParser()
    path = os.path.split(os.path.realpath(__file__))[0] + '/db.conf'
    config.read(path)    #虽然是写文件但是一定要先进行读操作,不然下一步会报找不到section的错误
    config.set(section,key,value)
    config.write(open(path,"w")) #最后写进文件,传入的参数要是一个文件对象

 

 

jlqwer

这个人很懒,什么都没留下

文章评论