0

Im new to this wonderful site. Kudos to the team here! I'm a python beginner!

Im trying to match a string in a file. im using re.match. it does work for other strings in the file except the one im interested into.

file has:

Dumping
..
..
Dumped

coordinates (.. ..)
..
..
EOF

i tried below script:

import re

f1 = open("problem_statment", "r") 
f2 = open("outfile.txt", "w")

for line in f1:
   if re.match("coordinates", line):
      f2.write(line)

the outfile doesn't give me the result of 'coordinates' match.., where as if i replace 'coordinates' in above code to 'Dumping', it matches..

Im clueless why it isn't matching 'coordinates'. i want to print whole line.. please guide!

Thanks!

DYZ
  • 55,249
  • 10
  • 64
  • 93
TgP
  • 1
  • 1
  • Can't reproduce from your input data. Are you sure about the input you've provided here is correct and exactly formatted? – heemayl Feb 05 '18 at 22:33
  • Yes, its the same input in the file im giving. there is two spaces for coordinates like: space space coordinates : – TgP Feb 05 '18 at 22:44

3 Answers3

3

You don't need to use the re module for this. You can just write

if 'coordinates' in line:
    f2.write(line)
Matias Cicero
  • 25,439
  • 13
  • 82
  • 154
rbennell
  • 1,134
  • 11
  • 14
0

Look at the difference between re.match and re.search. Look at this post https://stackoverflow.com/a/180993/8382967

Mathieu Kb
  • 23
  • 4
0

The problem with re.match is it only search at beginning of the string. Not in newlines . But your desired string is in newline.

You can use re.search() or re.findall() method.

import re
pattern=r'coordinates.+'
with open('file.txt','r') as f:
    print(re.findall(pattern,f.read()))

output:

['coordinatessss (.. ..)']
Aaditya Ura
  • 12,007
  • 7
  • 50
  • 88