python – 将变量值更改为在.INI文件中浮动

我正在使用.INI文件使用BASIC将变量从
Python传递到软件,在分析数据时,我想更新某些变量的值.

这是我目前的代码:

import numpy as np

try:
    from configparser import ConfigParser
except ImportError:
    from ConfigParser import ConfigParser

config = ConfigParser()
config.read('ParameterFile.ini')

# read values from a section
GainAff = config.getfloat('Section 1', 'gainaff')
GainVff = config.getfloat('Section 1', 'gainvff')
FeedforwardAdvance = config.getfloat('Section 1', 'feedforwardadvance')
TrajectoryFIRFilter = config.getfloat('Section 1', 'trajectoryfirfilter')
RampRate = config.getfloat('Section 1', 'ramprate')

print 'GainAff = ', GainAff
print 'GainVff = ', GainVff
print 'Feedforward Advance = ', FeedforwardAdvance
print 'Trajectory FIR Filter = ', TrajectoryFIRFilter
print 'Ramp Rate = ', RampRate

new_GainAff = 1.0
new_GainVff = 2.0
new_FeedforwardAdvance = 0.3
new_TrajectoryFIRFilter = 0.5
new_RampRate = 4000

##update existing value
config.set('Section 1', 'GainAff', new_GainAff)
config.set('Section 1', 'GainVff', new_GainVff)
config.set('Section 1', 'FeedforwardAdvance', new_FeedforwardAdvance)
config.set('Section 1', 'TrajectoryFIRFilter', new_TrajectoryFIRFilter)
config.set('Section 1', 'RampRate', new_RampRate)

##save to a file
with open('ParameterUpdate.ini', 'w') as configfile:
    config.write(configfile)
    ## Write some stuff in here
configfile.close()

但是,当我尝试使用config.set设置我的新变量时,我被告知我不能使用浮点值:

  File "/home/pi/.local/lib/python2.7/site-packages/backports/configparser/__init__.py", line 1221, in _validate_value_types
    raise TypeError("option values must be strings")
TypeError: option values must be strings

看了这个,我看到很多人使用带浮动的config.set,我不确定它是否因为python的版本等(我使用的是Python 2.7.13)

我究竟做错了什么?

最佳答案 set函数需要一个字符串:
https://docs.python.org/2/library/configparser.html

使用以下代码转换为字符串:

config.set('Section 1', 'GainAff', str(new_GainAff))

从我在这里读到的,这似乎也是python 3:https://docs.python.org/3/library/configparser.html的情况

可以确认这也是python 3的情况.以下是我的python 3解释器的输出:

>>> config = ConfigParser()
>>>
>>> config.read('b.ini')
['b.ini']
>>> config.set('Section 1', 'GainAff', 1.2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\PYTHON34\LIB\configparser.py", line 1165, in set
    self._validate_value_types(option=option, value=value)
  File "C:\PYTHON34\LIB\configparser.py", line 1154, in _validate_value_types
    raise TypeError("option values must be strings")
TypeError: option values must be strings
点赞