Created
March 2, 2017 16:13
-
-
Save janpipek/cec3a85552ac72f70a2febc0b54606f2 to your computer and use it in GitHub Desktop.
Functional head & tail in Python
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
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