Skip to content

Instantly share code, notes, and snippets.

@janpipek
Created March 2, 2017 16:13
Show Gist options
  • Save janpipek/cec3a85552ac72f70a2febc0b54606f2 to your computer and use it in GitHub Desktop.
Save janpipek/cec3a85552ac72f70a2febc0b54606f2 to your computer and use it in GitHub Desktop.
Functional head & tail in Python
from itertools import islice
from toolz.itertoolz import sliding_window, last
import codecs
import os
def head(path, n=10, encoding="utf-8"):
with codecs.open(os.path.expanduser(path), encoding=encoding) as f:
yield from map(lambda x: x.rstrip(), islice(f, n))
def tail(path, n=10, encoding="utf-8"):
with codecs.open(os.path.expanduser(path), encoding=encoding) as f:
lines = last(sliding_window(n, f))
yield from map(lambda x: x.rstrip(), lines)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment