将变量值更改为在.INI Fi中浮动

2024-10-04 05:24:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用一个.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设置新变量时,我被告知不能使用float值:

^{pr2}$

在查找这篇文章时,我看到很多人将config.set与float一起使用,我不确定是否是因为python的版本,等等(我使用的是python2.7.13)

我做错什么了?在


Tags: fromimportconfignewsectionconfigparserprintset
1条回答
网友
1楼 · 发布于 2024-10-04 05:24:14

{a1函数需要一个set} 使用以下代码将其转换为字符串:

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

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

可以确认Python3也是如此。以下是python3解释器的输出:

^{pr2}$

相关问题 更多 >