Created
August 7, 2015 20:59
-
-
Save htv2012/5324a6d1bdf82a7943f3 to your computer and use it in GitHub Desktop.
Given a text file, provide a quick and easy way to return a range of lines
This file contains 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
""" | |
Given a text file, provide a quick and easy way to return a range of | |
lines | |
""" | |
from itertools import islice | |
def select_lines(iterable, start_line, last_line): | |
# text lines usually 1-based, whereas islice is 0-base ==> -1 | |
return islice(iterable, start_line - 1, last_line) | |
# | |
# Test it out: we want lines 5-10 inclusive | |
# | |
START_LINE = 5 | |
LAST_LINE = 10 | |
with open('data.txt') as f: | |
for line in select_lines(f, START_LINE, LAST_LINE): | |
print line.strip() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Alternately, we can use
linecache