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设计】。

相关文章

python遍历小写英文字母的方法

在c、c++等语言中,可以用字符+1的for循环来遍历小写的26个英文字母,但是由于python语言的特殊性,通过a + 1这种代码并不能成功遍历,以下是在python中遍历英文字母的简...

python处理Excel xlrd的简单使用

xlrd主要用于读取Excel文件,本文为大家分享了python处理Excel的具体代码,供大家参考,具体内容如下 安装 pip install xlrd api使用 im...

Python中文分词工具之结巴分词用法实例总结【经典案例】

Python中文分词工具之结巴分词用法实例总结【经典案例】

本文实例讲述了Python中文分词工具之结巴分词用法。分享给大家供大家参考,具体如下: 结巴分词工具的安装及基本用法,前面的文章《Python结巴中文分词工具使用过程中遇到的问题及解决方...

利用Python画ROC曲线和AUC值计算

利用Python画ROC曲线和AUC值计算

前言 ROC(Receiver Operating Characteristic)曲线和AUC常被用来评价一个二值分类器(binary classifier)的优劣。这篇文章将先简单的介...

对python的输出和输出格式详解

对python的输出和输出格式详解

输出 1. 普通的输出 # 打印提示 print('hello world') 用print()在括号中加上字符串,就可以向屏幕上输出指定的文字。比如输出'hello, world...