从/mnt目录下读取section配置文件sample.ini
[db] host=192.168.1.116 hostaddr=192.168.1.116 port=5432 dbname=class4_db user=class4_user password = [web_db] host=db.$hostaddr port=db.$port dbname=db.$dbname user=db.$user password=db.$password
代码:
import os import ConfigParser os.chdir('/mnt') config=ConfigParser.ConfigParser() cfgfile=open("sample.ini","rw") config.readfp(cfgfile) db_host=config.get("db","host") db_user=config.get("db","user") print(db_host) print(db_user) config.set("db","host","192.168.1.1") config.set("db","port","21") db_host=config.get("db","host") db_port=config.get("db","port") print(db_host) print(db_port)
cfgfile.close()
执行结果:
/usr/bin/python2.7 /home/alex/PycharmProjects/py2_practise/ini_modify.py 192.168.1.116 class4_user 192.168.1.1 21 Process finished with exit code 0