python配置文件的写入

python配置文件有.conf,.ini,.txt等多种

python集成的 标准库的 ConfigParser 模块提供一套 API 来读取和操作配置文件

我的配置文件如下

 1 [MOTOR]
 2 comnum = 3
 3 baud = 19200
 4 m1slowstep = 10
 5 m1faststep = 100
 6 m1origin = 5
 7 m2slowstep = 10
 8 m2faststep = 50
 9 m2origin = 5
10 
11 [CoarseAdjust]
12 standardx = 0.000000
13 standardy = 0.000000
14 xperangle = 500
15 yperangle = 160
16 xmotor = 1
17 xmotororien = -1
18 ymotor = 2
19 ymotororien = 1
20 triggermode = 1
21 triggertimeout = 1
22 autoadjust = 1
23 
24 [FineAdjust]
25 countdown = 10
26 datfilepath = E:\Mcs05\DatTemp\
27 xfinestep = 10
28 yfinestep = 10
29 mcsfilepath = E:\Mcs05\WHTest\
30 filetype = Mcs
31 nastartaltitude = 80
32 naendaltitude = 111
33 rayleighstartaltitude = 20
34 rayleighendaltitude = 60
35 fineadjustfilepath = E:\Mcs05\
36 methodselect = 01
37 
38 [EASYMCS]
39 chname = WHTest
40 prefixion = R
41 mcstheshold = 1.4
42 numofbins = 2048
43 binwidth = 640
44 numofpluse = 30
45 mcs32path = D:\software\MCS32\
46 mcs32filepath = E:\Mcs05\
47 
48 [GYRO]
49 comno = 15
50 baud = 9600

当我进行读写操作时,发现

 1 # 读取配置文件
 2 import ConfigParser
 3 config = ConfigParser.ConfigParser()
 4 config.readfp(open('GloVar.ini'))
 5 a = config.get("CoarseAdjust","MD5")
 6 print a
 7 
 8 # 写入配置文件
 9 import ConfigParser
10 config = ConfigParser.ConfigParser()
11 # set a number of parameters
12 config.add_section("CoarseAdjust")
13 config.set("CoarseAdjust", "xperangle", "1000")
14 config.set("CoarseAdjust", "yperangle", "500")

发现配置文件中的内容并没有发生改变,为什么?

上面的这种修改方式只是修改了python中内存的值,并没有对配置文件的内容进行修改,并真实地写入

真正地修改方式应该是

 1 """修改并保存在配置文件中"""
 2 # coding:utf-8
 3 import configparser
 4 
 5 # 创建管理对象
 6 conf = configparser.ConfigParser()
 7 conf.read('GloVar.ini', encoding='utf-8')
 8 print(conf.sections())
 9 
10 # 往section添加key和value
11 conf.set("CoarseAdjust", "xPerAngle", "{}".format(500))
12 conf.set("CoarseAdjust", "yPerAngle", "160")
13 items = conf.items('CoarseAdjust')
14 print(items) # list里面对象是元祖
15 
16 conf.write(open('GloVar.ini', "r+", encoding="utf-8"))  # r+模式

ConfigParser 模块需要注意的是

  • 不能区分大小写。
  • 重新写入的配置文件不能保留原有配置文件的注释。
  • 重新写入的配置文件不能保持原有的顺序。
  • 不支持嵌套。
  • 不支持格式校验

本文参考了

https://blog.csdn.net/weixin_33827590/article/details/93565730

https://blog.csdn.net/tw18761720160/article/details/78753101

猜你喜欢

转载自www.cnblogs.com/hkpcn/p/11703267.html