Skip to content

Instantly share code, notes, and snippets.

@bbengfort
Created August 14, 2014 16:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bbengfort/a55dd4341e00719e5f6f to your computer and use it in GitHub Desktop.
Save bbengfort/a55dd4341e00719e5f6f to your computer and use it in GitHub Desktop.
A CSV reader that can handle different field lables
first_name last_name email
ben bengfort bbengfort@gmail.com
sean murphy murphsp1@gmail.com
bob jones bob@example.com
name email
ben bbengfort@gmail.com
sean murphsp1@gmail.com
bob bob@example.com
# pkg.mod
# description
#
# Author: Benjamin Bengfort <benjamin@bengfort.com>
# Created: timestamp
#
# Copyright (C) 2014 Bengfort.com
# For license information, see LICENSE.txt
#
# ID: reader.py [] benjamin@bengfort.com $
"""
"""
##########################################################################
## Imports
##########################################################################
import unicodecsv as csv
##########################################################################
## Reader/Remapper
##########################################################################
class Reader(object):
"""
Reads rows and spits out a row mapper
"""
def __init__(self, path):
self.path = path
def __iter__(self):
with open(self.path, 'rU') as data:
reader = csv.DictReader(data)
for row in reader:
yield RowMapper(row)
class RowMapper(object):
"""
Maps rows to the correct dictionary keys
"""
def __init__(self, data):
self.data = data
@property
def name(self):
if 'name' in self.data:
return self.data['name']
elif 'first_name' in self.data:
if 'last_name' in self.data:
return " ".join([self.data['first_name'], self.data['last_name']])
else:
return self.data['first_name']
@property
def email(self):
"""
This sucks - we'd have to right a property for everything we were
expecting, and it will ignore things we miss; there is a more
generic way to do this!
"""
return self.data.get('email', None)
if __name__ == '__main__':
reader = Reader('emails.csv')
for row in reader:
print "%s <%s>" % (row.name, row.email)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment