1

次のようなテキスト ファイル (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_phase、他はsample_gain_hi何も変更せずに。Pythonでこれを行うにはどうすればよいですか? どうもありがとう、

4

2 に答える 2

2

モジュールを使用でき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()
于 2013-06-12T14:12:16.100 に答える
0

mmap を使用してこれを行うこともできます (1 つの注意点として、更新された行は古い行と同じ長さが必要になるため、スペースを埋め込む必要がある場合があります)。

>>> import mmap
>>> f = open("config.conf", "r+b")
>>> mm = mmap.mmap(f.fileno(), 0)
>>> mm.find("sample_gain_hi")
134
>>> new_line = "sample_gain_hi = 999"
>>> mm[134:134+len(new_line)] = new_line
>>> mm.close()
>>> f.close()
于 2013-06-12T15:03:21.313 に答える