Last active
August 29, 2015 14:13
-
-
Save radzhome/55d94949459b1065e95f to your computer and use it in GitHub Desktop.
First Gist: Process a CSV File in Python/Django
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Test Gist | |
import csv | |
from models import RegistrationCode | |
REQUIRED_FIELDNAMES = frozenset([ | |
'Registration code', | |
]) | |
def process_row(row): | |
if len(row) == 1: | |
reg_key = list(row.keys())[0] | |
else: | |
reg_key = 'Kraft Registration code' | |
reg_code, _ = RegistrationCode.objects.get_or_create(code=row[reg_key]) | |
reg_code.save() | |
return 'imported %s' % reg_code.code | |
def process_file(csv_file): | |
reader = csv.DictReader(csv_file.read().splitlines()) | |
csv_headers = frozenset(reader.fieldnames) | |
if REQUIRED_FIELDNAMES.issubset(csv_headers) or len(csv_headers) == 1: | |
res = map(process_row, reader) | |
return '\n\n'.join(res) | |
else: | |
return '**INVALID DATA FILE**' | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment