时间:2020-10-04 14:44:07 | 栏目:Python代码 | 点击:次
python配置文件有.conf,.ini,.txt等多种
python集成的 标准库的 ConfigParser 模块提供一套 API 来读取和操作配置文件
我的配置文件如下
[MOTOR] comnum = 3 baud = 19200 m1slowstep = 10 m1faststep = 100 m1origin = 5 m2slowstep = 10 m2faststep = 50 m2origin = 5 [CoarseAdjust] standardx = 0.000000 standardy = 0.000000 xperangle = 500 yperangle = 160 xmotor = 1 xmotororien = -1 ymotor = 2 ymotororien = 1 triggermode = 1 triggertimeout = 1 autoadjust = 1 [FineAdjust] countdown = 10 datfilepath = E:\Mcs05\DatTemp\ xfinestep = 10 yfinestep = 10 mcsfilepath = E:\Mcs05\WHTest\ filetype = Mcs nastartaltitude = 80 naendaltitude = 111 rayleighstartaltitude = 20 rayleighendaltitude = 60 fineadjustfilepath = E:\Mcs05\ methodselect = 01 [EASYMCS] chname = WHTest prefixion = R mcstheshold = 1.4 numofbins = 2048 binwidth = 640 numofpluse = 30 mcs32path = D:\software\MCS32\ mcs32filepath = E:\Mcs05\ [GYRO] comno = 15 baud = 9600
当我进行读写操作时,发现
# 读取配置文件 import ConfigParser config = ConfigParser.ConfigParser() config.readfp(open('GloVar.ini')) a = config.get("CoarseAdjust","MD5") print a # 写入配置文件 import ConfigParser config = ConfigParser.ConfigParser() # set a number of parameters config.add_section("CoarseAdjust") config.set("CoarseAdjust", "xperangle", "1000") config.set("CoarseAdjust", "yperangle", "500")
发现配置文件中的内容并没有发生改变,为什么?
上面的这种修改方式只是修改了python中内存的值,并没有对配置文件的内容进行修改,并真实地写入
真正地修改方式应该是
"""修改并保存在配置文件中""" # coding:utf-8 import configparser # 创建管理对象 conf = configparser.ConfigParser() conf.read('GloVar.ini', encoding='utf-8') print(conf.sections()) # 往section添加key和value conf.set("CoarseAdjust", "xPerAngle", "{}".format(500)) conf.set("CoarseAdjust", "yPerAngle", "160") items = conf.items('CoarseAdjust') print(items) # list里面对象是元祖 conf.write(open('GloVar.ini', "r+", encoding="utf-8")) # r+模式
ConfigParser 模块需要注意的是