Skip to content

Instantly share code, notes, and snippets.

@pavelpy
Created February 15, 2018 19:18
Show Gist options
  • Save pavelpy/f2cd0dff10bdb1b1c3da2c9648e5f04e to your computer and use it in GitHub Desktop.
Save pavelpy/f2cd0dff10bdb1b1c3da2c9648e5f04e to your computer and use it in GitHub Desktop.
# Original source: Raymond's Hettinger tweet
""" #python lets you run for-loops over partially consumed iterators.
This is useful for extracting and skipping over header rows:
"""
it = iter(f)
header = next(it)
for line in it:
...
# Original source: @julienbaley tweet
"""itertools' doc has this great recipe to skip n items:"""
def consume(iterator, n):
next(islice(iterator, n, n), None)
# Original source: @gumnos tweet
"""Use this regularly. Also its cousin:"""
r = csv.reader(f)
for row in r: # skip preamble, search for the header row
 if EXPECTED_HEADER in row:
  headers = row
  for row in r: # exhaust "r"
   yield dict(zip(headers, row))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment