0

I wrote the following code in Python to match string inside files:

#!/usr/bin/python

import re

f = open('file','r')
for line in f:
    mat = re.search(r'This',line)
    mat.group(0)
f.close()

I used the following file as input:

This is the first line
That was the first line

But when I try to search for the expression This it results in None output. Why isn't the string is not matching?

Adem Öztaş
  • 20,457
  • 4
  • 34
  • 42
sarthak
  • 774
  • 1
  • 11
  • 27

2 Answers2

1

You should be using the with syntax to make sure files are opened properly.

You didn't check to see if there was a match first so it would crash when it checked the second line. Here is some working code:

import re

with open('file','r') as f:
    for line in f:
        mat = re.search(r'This',line)
        if mat:
            print mat.group(0)
muddyfish
  • 3,530
  • 30
  • 37
  • what is the difference between the two ways of opening a file?? – sarthak Aug 24 '15 at 09:48
  • @sarthak You don't need to close the file descriptor in this case – Harman Aug 24 '15 at 09:58
  • @sarthak It also closes the file if an exception is raised. It is generally considered better. Also see http://stackoverflow.com/questions/1369526/what-is-the-python-keyword-with-used-for – muddyfish Aug 24 '15 at 10:16
1

I prefer compiling the pattern beforehand, and use it at each iteration.

import re

pat = re.compile(r'This')

with open('file') as f:
    for line in f:
        mat = pat.search(line)
        if mat:
            print(mat.group(0))
tilacog
  • 663
  • 7
  • 14