Last active
July 14, 2016 02:23
-
-
Save mikkkee/cf539b6bcc44c0aa7643 to your computer and use it in GitHub Desktop.
Read file N lines at a time
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
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