Skip to content

Instantly share code, notes, and snippets.

@mikkkee
Last active July 14, 2016 02:23
Show Gist options
  • Save mikkkee/cf539b6bcc44c0aa7643 to your computer and use it in GitHub Desktop.
Save mikkkee/cf539b6bcc44c0aa7643 to your computer and use it in GitHub Desktop.
Read file N lines at a time
import string
from itertools import islice
def next_n_lines(file_opened, N, strip='right'):
'''
Each call of this function returns next N lines of fileopen.
Usage:
strip='right' -> remove trailing whitespace characters in each line,
strip='left' -> remove leading whitespace characters in each line,
strip='both' -> remove both trailing and leading whitespace characters in each line,
strip=None -> do not remove any characters.
Note: CANNOT be used together with readline() or readlines() method.
'''
strip_dic = {
'right': string.rstrip,
'left': string.lstrip,
'both': string.strip
}
if strip:
return [strip_dic[strip](x) for x in islice(file_opened, N)]
else:
return list(islice(file_opened, N))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment