Skip to content

Instantly share code, notes, and snippets.

@vstoykov
Last active August 9, 2017 11:41
Show Gist options
  • Save vstoykov/ff4d487d520b1b43ec03 to your computer and use it in GitHub Desktop.
Save vstoykov/ff4d487d520b1b43ec03 to your computer and use it in GitHub Desktop.
Parsing CSV files
"""
Easy parsing of CSV files.
Every row is a named tuple with column name defined by the header (first row).
By default header is not returned (only rows containing the data)
"""
import csv
from collections import namedtuple
def parse_csv_file(file_name, has_header=True, return_header=False):
with open(file_name, newline='', encoding='utf-8') as csvfile:
csvreader = csv.reader(csvfile)
if has_header:
header = next(csvreader)
Row = namedtuple('Row', header)
if return_header:
yield header
else:
Row = tuple
for row in csvreader:
yield Row(*row)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment