0

I have a text file named "filename.txt"

content of file:

    This is just a text
    content to store
    in a file.

i have made two python scripts to extract "to" from the text file

my 1st script:

     #!/usr/bin/python
     import re
     f = open("filename.txt","r")
     for line in f:
              text = re.match(r"content (\S+) store",line)
              x = text.group(1)
              print x

my 2nd script:

    #!/usr/bin/python
    import re
    f = open("filename.txt","r")
    for line in f:
             text = re.match(r"content (\S+) store",line)
             if text:
                    x = text.group(1)
                    print x

2nd script gives the correct output

 bash-3.2$ ./script2.py
 to

but 1st script gives me an error

bash-3.2$ ./script1.py
Traceback (most recent call last):
File "./script1.py", line 6, in ?
x = text.group(1)
AttributeError: 'NoneType' object has no attribute 'group'

how is that adding an "if" condition gives me the correct output and when i remove it i get an error?

2 Answers 2

1

The error is pretty self-explanatory to me: re.match returns None if no match is found (see doc).

So when your regex doesn't match (eg first line), you're trying to access the group property of a NoneType object, it throws an error.

In the other case, you only access the property if text isn't None (since this is what the if text: checks, among other things).

Sign up to request clarification or add additional context in comments.

Comments

1

This is because in your first code, your regex fails to match anything and therefore text is a NoneType. When you try to do group it throws the AttributeError: 'NoneType' object has no attribute 'group' error

However, for your regex, your code doesn't fail because you are careful to call group only if something was actually matched

Your second method is better since it's fail proof unlike the first one.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.