destrudos
destrudos

Reputation: 37

Python and regex - search in file

Assume I have some text in *.txt file:

NUM_SITE_CHAINS 1
SITE_DESCR EVIDENCE_CODE: SOFTWARE BINDING  FOR RESIDUE ZN A 179
NUMBER_OF_AA 4 22
EXPOSURE   0.45   0.26
DISCONTINUITY 18.000
SITE -3.275 0.375 -0.525 0.125 44.400 57.400 44.725 21.700
ENVIRONMENT 0.718 -0.232 0.138 0.000 40.164 28.782 55.655 42.505

I want to find line starting with "SITE" In my example it will be 6-th line. I don't want to find the second line because there is no space after "SITE". To do that I tried something like this:

with open(fname) as openfile:
    for line in openfile:
        for part in line.split():
            if re.search(r"^SITE\s", part):
                listSITE.append(line)

But the "listSITE" remain empty. Is there a problem with regex expression or in inappropriate re. method? Thank you in advance!

Upvotes: 0

Views: 47

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521259

Use re.findall, with the pattern ^SITE .*$:

input = "..."
lines = re.findall(r'^SITE .*$', input, flags=re.MULTILINE)
print(lines)

['SITE -3.275 0.375 -0.525 0.125 44.400 57.400 44.725 21.700']

Upvotes: 1

E.Serra
E.Serra

Reputation: 1574

with open(fname) as openfile:
    for line in openfile:
        if line.startswith('SITE '):
            listSITE.append(line)

No need to import re, just use startswith (note the space at the end of the SITE str.

Upvotes: 1

Related Questions