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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM