It looks to me like the problem is that you're always testing if the text matches match
:
So, let's simplify a bit. What happens with the following code?:
match = None
if match:
# The interpreter will never get here because `match` is None, which
# evaluates to False when in an `if`
print >> take, match.group(1)
elif match:
# This `elif` is still testing against `match`, which is still None,
# therefore, evaluated to false.
print >> take, match2.group(1)
elif match:
# Same drill here...
print >> take, match3.group(1)
I'm guessing you want to do:
if match:
print >> take, match.group(1)
elif match2:
print >> take, match2.group(1)
elif match3:
print >> take, match3.group(1)
EDIT:
Maybe the following code will help you understand what's happening. The code below transforms yours by doing two things:
- Read the input file line by line
- Match each line to each of the three expressions
With those changes, the code would look like:
import re, os
mykey = open("text.txt", "r")
take = open("take.txt", "w")
print "I have opened a file object to read stuff. That is: %s" % mykey
print "I have opened a file object to write stuff. That is: %s" % take
for text in mykey:
print "I have read the line: %s" % text
match = re.search('"JOL":"(.+?).tr', text)
match2 = re.search('"CRY":"(.+?).tr', text)
match3 = re.search('"LAY":"(.+?).tr', text)
if match:
print >> take, match.group(1)
elif match2:
print >> take, match2.group(1)
elif match3:
print >> take, match3.group(1)
If text.txt
contains the following:
"JOL":"foo1".tr
"CRY":"bar1".tr
"LAY":"baz1".tr
"LAY":"baz2".tr
"CRY":"bar2".tr
"JOL":"foo2".tr
The contents found in take.txt
after you run this script will be:
foo1"
bar1"
baz1"
baz2"
bar2"
foo2"
I have added some print
statements that maybe will help you understand a bit what's going on. Check your terminal and see if that "extra debug" output helps you follow what's happening in the code.
You should also try to understand how file objects (input-output, in general) works in Python.