python配置文件写入过程详解

yipeiwu_com6年前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 模块需要注意的是

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python3.7基于hashlib和Crypto实现加签验签功能(实例代码)

环境: Python3.7 依赖库: import datetime import random import requests import hashlib import json...

Linux 发邮件磁盘空间监控(python)

核心代码: #!/usr/bin/python # -*- coding: UTF-8 -*- import smtplib import os import commands,...

Python使用pygame模块编写俄罗斯方块游戏的代码实例

Python使用pygame模块编写俄罗斯方块游戏的代码实例

文章先介绍了关于俄罗斯方块游戏的几个术语。 边框——由10*20个空格组成,方块就落在这里面。 盒子——组成方块的其中小方块,是组成方块的基本单元。 方块——从边框顶掉下的...

python之django母板页面的使用

其实就是利用{% block xxx %}   {% endblock %}的方式定义一个块,相当于占位。存放在某个html中,比如base.html 然后在需要实现...

对Python 中矩阵或者数组相减的法则详解

对Python 中矩阵或者数组相减的法则详解

最近在做编程练习,发现有些结果的值与答案相差较大,通过分析比较得出结论,大概过程如下: 定义了一个计算损失的函数: def error(yhat,label): yhat = np...