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>Alternatively, since you have a <code>csv</code> file you could use the <code>csv</code> module:</p>

<pre><code>import csv
import io

file = io.StringIO(u'''
19940325\t78\t-28\t-9999
19940326\t50\t17\t102
19940327\t100\t-11\t-9999
19940328\t56\t-33\t0
19940329\t61\t-39\t-9999
19940330\t61\t-56\t0
19940331\t139\t-61\t-9999
19940401\t211\t6\t0
'''.strip())

reader = csv.reader(file, delimiter='\t')
for row in reader:
    if row[-1] == '-9999':   # or, for regex, `re.match(r'^-9999$', row[-1])`
        print('\t'.join(row))
</code></pre>

python python-2.7 python-3.x