Created
January 30, 2018 15:46
-
-
Save dvska/b60184d8c2f4b3224a33ffb3c462530b to your computer and use it in GitHub Desktop.
OOcsv: object view of CSV
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
"""OOcsv: object view of CSV | |
~5 times faster than OODict | |
2013 Dmitry V. Selitsky d.v.selitsky@gmail.com / dvska-at-skype | |
""" | |
from collections import namedtuple | |
def OOcsv(csv_file_obj, use_unicodecsv=False, **kwargs): | |
if use_unicodecsv: | |
import unicodecsv as csv | |
else: | |
import csv | |
head = next(csv_file_obj).replace(' ', '_').replace('"', '').replace(';', ',') | |
csv_data = csv.reader(csv_file_obj, **kwargs) | |
Record = namedtuple('Record', head, rename=True) | |
#for oo_row in (Record._make(x) for x in csv_data): | |
# yield oo_row | |
return (Record._make(x) for x in csv_data) | |
# Usage: | |
# | |
# with open("Batting.csv") as f: | |
# for r in OOcsv(f): | |
# if r.yearID=='1977': pass | |
# pprint( tuple( | |
# OOcsv(StringIO(raw_csv.encode('utf8')), | |
# delimiter=';', quoting=csv.QUOTE_ALL))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment