with open(myfilename, 'rb') as f: LogLine = namedtuple('LogLine','fqdn,ip,user') for line in map(LogLine._make, csv.reader(f)): print 'user %s visited %s from %s' % (line.user, line.fqdn, line.ip)What's going on here?
- csv.reader(f) reads from the file descriptor f line-by-line and returns an array like ['user','blah.com','192.168.1.1']
- We use map to call LogLine._make on each member of the csv iterator (i.e. each line), which creates a LogLine tuple from the array.
- No need to split() and strip(), the csv reader figures it out for you.
- No referring to line, line etc. forgetting which one is which, and having to change a bunch of code if you add a field or the order changes. The tuple gives you names that are human readable and the file structure is contained in one place, the tuple constructor, so changes to fields are simple.
- Also, if you aren't familiar with the 'with' statement, it is very nice for working with files since it replaces the 'try: read, finally: close' boilerplate code.