shantanuo
shantanuo

Reputation: 32316

attribute groups does not belong to object

The following code works as expected if I declare the "line" variable at the beginning of the script. something like ...

s = "Jul 15 12:12:51 whitelist logger: 1|999999999999|id:d9faff7c-4016-4343-b494-37028763bb66 submit date:1307130919 done date:1307130919 stat:DELIVRD err:0|L_VB3_NM_K_P|1373687445|vivnel2|L_VB3_GH_K_P|promo_camp1-bd153424349bc647|1"

When I open a file and loop through lines, the groups attribute does not work. I get an error:AttributeError: 'NoneType' object has no attribute 'groups'

# cat mylast.py
import re

f = open('customer.csv')

for line in f:

      logger_re = re.compile(
     "logger: ([^ ]+)\
      submit date:(\d+)\
      done date:(\d+)\
      stat:(.+)\
      err:(.+)$")
      myvalues = logger_re.search(line).groups()
      print myvalues

f.close()

Exception:

# python mylast.py
Traceback (most recent call last):
  File "mylast.py", line 13, in ?
    myvalues = logger_re.search(line).groups()
AttributeError: 'NoneType' object has no attribute 'groups'

Upvotes: 0

Views: 72

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121972

Your regular expression is not matching your actual file contents.

As such, logger_re.search(line) returns None.

The problem here is that you indented your regular expression but did not compensate for the extra whitespace:

logger_re = re.compile(
     "logger: ([^ ]+)\
      submit date:(\d+)\
      done date:(\d+)\
      stat:(.+)\
      err:(.+)$")

Note that the whitespace at the start of the line there matters. Use separate strings (Python will join them at compile time):

logger_re = re.compile(
     "logger: ([^ ]+) "
     "submit date:(\d+) "
     "done date:(\d+) "
     "stat:(.+) "
     "err:(.+)$")

Upvotes: 2

Sam Nicholls
Sam Nicholls

Reputation: 899

Your search will return None if no matches were found. You need to check that myvalues is not None before attempting to access groups().

Upvotes: 0

Related Questions