How to search a word in a file and replace the entire line with a new line?
<p>I have a file (with extension.hgx) that has some data like this:</p>

<pre><code>length             =  0.00000783
height             =  48
RATIO              =  2
X                  =  1.0
Y                  =  1.0
</code></pre>

<p>I would like to open the file and replace the two lines:</p>

<hr>

<pre><code>height             =  48
RATIO              =  2
</code></pre>

<hr>

<p>With:</p>

<hr>

<pre><code>height             =  8
RATIO              =  8
</code></pre>

<hr>

<p>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</p>

<p>I have written the following code</p>

<pre><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) &gt;= 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
</code></pre>

<p>This does not help replace complete line and save the file again. returns empty file.Any help would be greatly appreciated.</p>

<p>Regards,
Ris</p>
