Fix Python – What is the perfect counterpart in Python for “while not EOF” [duplicate]


Asked By – Allen Koo

To read some text file, in C or Pascal, I always use the following snippets to read the data until EOF:

while not eof do begin

Thus, I wonder how can I do this simple and fast in Python?

Now we will see solution for issue: What is the perfect counterpart in Python for “while not EOF” [duplicate]


Loop over the file to read lines:

with open('somefile') as openfileobject:
    for line in openfileobject:

File objects are iterable and yield lines until EOF. Using the file object as an iterable uses a buffer to ensure performant reads.

You can do the same with the stdin (no need to use raw_input():

import sys

for line in sys.stdin:

To complete the picture, binary reads can be done with:

from functools import partial

with open('somefile', 'rb') as openfileobject:
    for chunk in iter(partial(, 1024), b''):

where chunk will contain up to 1024 bytes at a time from the file, and iteration stops when starts returning empty byte strings.

This question is answered By – Martijn Pieters

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0