I have a file (with extension.hgx) that has some data like this:
length = 0.00000783
height = 48
RATIO = 2
X = 1.0
Y = 1.0
I would like to open the file and replace the two lines:
height = 48
RATIO = 2
With:
height = 8
RATIO = 8
I tried parsing the file and could search for the “height” and “RATIO”. Unfortunately, I could not replace the line with new line and re-save the file. In my case the problem is that, that in the file the value of parameters e.g. height(=48) varies and sometimes has uneven spaces in between. I want to replace this complete line with–
height = 8
I have written the following code
import fileinput
import sys
f = open('test.hgx','r')
line_num = 0
search_phrase = "height"
for line in f.readlines():
line_num += 1
if line.find(search_phrase) >= 0:
print line_num
newline='height = 8'
lnum=1
for line in fileinput.FileInput("test.hgx",inplace=1):
if lnum==line_num:
result = newline+"\n"
else:
result=line
lnum=lnum+1
sys.stdout.write(result)
print line
This does not help replace complete line and save the file again. returns empty file.Any help would be greatly appreciated.
Regards,
Ris
How’s this?