Modifying Parameter In Existing Text File With Python
I have a text file (example.txt) which looks like this: 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 #sa
Solution 1:
You can use the fileinput
module:
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()
Solution 2:
You can also use mmap to do this ( one caveat is that your updated lines need the same length as the old ones -- so you might need to pad with spaces )
>>> 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()
Post a Comment for "Modifying Parameter In Existing Text File With Python"