How to read file N lines at a time in Python?
问题 I need to read a big file by reading at most N lines at a time, until EOF. What is the most effective way of doing it in Python? Something like: with open(filename, 'r') as infile: while not EOF: lines = [get next N lines] process(lines) 回答1: One solution would be a list comprehension and the slice operator: with open(filename, 'r') as infile: lines = [line for line in infile][:N] After this lines is tuple of lines. However, this would load the complete file into memory. If you don't want