Replace Line with New Line in Python
<p>I am reading a text file and searching data line by line, based on some condition, changing some values in the line and writing it back into another file. The new file should not contain the old Line. I have tried the following, but it did not work. I think I am missing a very basic thing.</p>

<p>Solution: In C++  we can increment line but in Python I am not sure how to achieve this. So as of now, I am writing old line than new line. But in the new file, I want only the new line.</p>

<p>Example:</p>

<pre><code>M0 38 A 19 40 DATA2 L=4e-08 W=3e-07 nf=1 m=1 $X=170 $Y=140 $D=8
M0 VBN A 19 40 TEMP2 L=4e-08 W=3e-07 nf=1 m=1 $X=170 $Y=140 $D=8 
</code></pre>

<p>The code which i tried is the following:</p>

<pre><code>def parsefile():
    fp = open("File1", "rb+")
    update_file = "File1" + "_update"
    fp_latest = open(update_file, "wb+")  
    for line in fp:
        if line.find("DATA1") == -1:
            fp_latest.write(line)
        if line.find("DATA1") != -1:
            line = line.split()
            pin_name = find_pin_order(line[1])
            update_line = "DATA " + line[1] + " " + pin_name
            fp_latest.write(update_line)
            line = ''.join(line) 
         if line.find("DATA2") != -1:
            line_data = line.split()
            line_data[1] = "TEMP2"
            line_data =' '.join(line_data)
            fp_latest.write(line_data)
         if line.find("DATA3") != -1:
            line_data = line.split()
            line_data[1] = "TEMP3"
            line_data =' '.join(line_data)
            fp_latest.write(line_data)

 fp_latest.close()
 fp.close()
</code></pre>
