python - 使用Python修改现有文本文件中的参数

标签 python

我有一个文本文件(example.txt),如下所示:

sn = 50
fs=60
bw=10
temperature=20
ch=10

rx_b_phase = 204c7a76
rx_b_gain  = 113
tx_b_phase = 01ff03e1
tx_b_gain  = 105

#sample_gain
sample_gain_hi = 7dc
sample_gain_mid = 7d0
sample_gain_low = 7c9

psl = 44
pin = -1728

#tmpr_reg   temperature,pa_reg,wfp_reg
tmpr_reg = 1,d4,1b
tmpr_reg = 6,d3,1b
tmpr_reg = 12,d2,1b
tmpr_reg = 17,d1,1b

我需要修改/更新以下参数:rx_b_phasesample_gain_hi,而不更改其他任何内容。我将如何使用 Python 来做到这一点? 非常感谢,

最佳答案

您可以使用fileinput模块:

import fileinput
for line in fileinput.input('example.txt', inplace = True):
    if line.startswith('rx_b_phase'):
        #if line starts with rx_b_phase then do something here
        print "rx_b_phase = foo"
    elif line.startswith('sample_gain_hi'):
        #if line starts with sample_gain_hi then do something here
        print "sample_gain_hi = bar"
    else:
        print line.strip()

关于python - 使用Python修改现有文本文件中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17067573/

相关文章:

python - 如何获取二维列表中元组的索引?

python - 从python访问WMI信息

python - 如何增加文件命名计数器?

c++ - python函数作为c++暴露类的参数使用::boost::python

python - 从 NumPy 数组到 Mat (OpenCV) 的 C++ 转换

python - 了解错误 : 'str' object is not callable

python - 迁移到 pygobject、glade 和 gtk3 时使用入口组合框

python - Django 表单;使用 ModelForm 覆盖选择

python - 如何使用适合的图像和剖面图创建 Matplotlib 图?

python读取并转换原始3D图像文件