Last active
August 9, 2017 11:41
-
-
Save vstoykov/ff4d487d520b1b43ec03 to your computer and use it in GitHub Desktop.
Parsing CSV files
This file contains hidden or 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
""" | |
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