Finding the exact string in input file
<p>I am looking for the lines starting with "ND" in an input file.
that looks like this:</p>

<pre><code>ND 195 4.53434033e+006 5.62453069e+006 2.56369141e+002
ND 196 4.53436645e+006 5.62443565e+006 2.56452118e+002
NS  129 113 97 82 58 59 37 22 17 18
NS  5 6 12 26 42 64 62 85 102 117
</code></pre>

<p>I wrote a code like this:</p>

<pre><code>from __future__ import print_function

found_ND = False
text = "ND"
with open('input.txt', 'r') as f, open('output.dat', 'w') as outfile:
    for line in f:
        if text in line:
           found_ND = True
        if found_ND:
            #do whatever you want
            try:
                line = line.strip()
                columns = line.split()
                i = float(columns[1])
                x = float(columns[2])
                y = float(columns[3])
                z = float(columns[4])
                print(z)
                print("{:.2f}".format(z), file=outfile)
            except ValueError:
                pass
</code></pre>

<p>But in the result I get also the fourth column of the string starting with "NS".
Result looks like this:</p>

<pre><code>256.37
256.45
82.00
26.00
</code></pre>

<p>How can I write the code to avoid the lines starting with <code>"NS"</code>?</p>

<p>Well, you're using a flag <code>found_ND</code>, making it <code>True</code> if the line is found (which happens for the first line) and then never change it back to <code>False</code>:        </p>

<pre><code>if text in line:
    found_ND = True
</code></pre>

<p><em><code>found_ND</code> will be <code>True</code> for all following iterations</em>. In short, just don't use a flag, you don't need it:</p>

<pre><code>for line in f:
    if text in line:
        #do whatever you want
        try:
            line = line.strip()
            columns = line.split()
            # .. and so on.
</code></pre>

<p>or, if you strictly want to check the beginning (that is, the line might contain <code>'ND'</code> elsewhere) use <code>startswith</code> as @Wiktor suggested:</p>

<pre><code>for line in f:
    if line.startswith('ND '):
        # ...
</code></pre>

python string python-3.x