How can I use regular expression when reading a text file in Python?
<p>I would like to give you an example. If I am trying to print lines that contain the integer <code>-9999</code> from a file.</p>

<pre><code>19940325       78     -28   -9999
19940326       50      17     102
19940327      100     -11   -9999
19940328       56     -33       0
19940329       61     -39   -9999
19940330       61     -56       0
19940331      139     -61   -9999
19940401      211       6       0
</code></pre>

<p>here is my code that uses regex to read the text file and scans  to find the integer <code>-9999</code> and print only the line/lines that contains that integer.</p>

<pre><code>import re

file= open("USC00110072.txt", "r")


for line in file.readlines():
    if re.search('^-9999$', line, re.I):
        print line
</code></pre>

<p>My code runs with error but doesn't show anything in the output. Please let me know what mistake i have made. </p>

<p>You can use <code>filter</code>:</p>

<pre><code>with open(fn) as f:
    print filter(lambda line: '-9999' in line.split()[-1], f)
</code></pre>

<p>This is will check if '-9999' is in the final column of the line. </p>

<p>If you want to use a regex:</p>

<pre><code>with open(fn) as f:
    for line in f:
        if re.search(r'-9999$', line): # remove $ if the -9999 can be anywhere in the line
            print line.strip()
</code></pre>

<p>The <code>^</code> you have will never match except for a line that only contains <code>-9999</code> and nothing else. The <code>^</code> indicates the start of the line. </p>

<p>Or, just use <code>in</code> to test the presence of the string:</p>

<pre><code>with open(fn) as f:
    for line in f:
        if '-9999' in line:
            print line.strip()
</code></pre>

python python-2.7 python-3.x