Skip to content

Instantly share code, notes, and snippets.

@htv2012
Created August 7, 2015 20:59
Show Gist options
  • Save htv2012/5324a6d1bdf82a7943f3 to your computer and use it in GitHub Desktop.
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
"""
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()
@htv2012
Copy link
Author

htv2012 commented Feb 28, 2017

Alternately, we can use linecache

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment