Skip to content

Instantly share code, notes, and snippets.

@karthicraghupathi
Created July 1, 2020 17:34
Show Gist options
  • Save karthicraghupathi/096debdf9f9a6a408c3d9442ac32c3b6 to your computer and use it in GitHub Desktop.
Save karthicraghupathi/096debdf9f9a6a408c3d9442ac32c3b6 to your computer and use it in GitHub Desktop.
CSV reader using generator with the ability to slice
def parse_csv_file(filename, start=0, stop=None, step=1):
"""
Parses a csv file.
start - elements from the iterable are skipped until start is reached
stop - if None, continue iteration until iterator is exhausted or until stop is reached
step - skip items before returning value; useful for skipping headers etc
"""
with open(filename, 'r') as csv_file:
for row in csv.DictReader(
itertools.islice(csv_file, start, stop, step), skipinitialspace=True
):
yield row
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment