Python: read all text file lines in loop

PythonFile

Python Problem Overview


I want to read huge text file line by line (and stop if a line with "str" found). How to check, if file-end is reached?

fn = 't.log'
f = open(fn, 'r')
while not _is_eof(f): ## how to check that end is reached?
    s = f.readline()
    print s
    if "str" in s: break

Python Solutions


Solution 1 - Python

There's no need to check for EOF in python, simply do:

with open('t.ini') as f:
   for line in f:
       # For Python3, use print(line)
       print line
       if 'str' in line:
          break

Why the with statement:

> It is good practice to use the with keyword when dealing with file > objects. This has the advantage that the file is properly closed after > its suite finishes, even if an exception is raised on the way.

Solution 2 - Python

Just iterate over each line in the file. Python automatically checks for the End of file and closes the file for you (using the with syntax).

with open('fileName', 'r') as f:
    for line in f:
       if 'str' in line:
           break

Solution 3 - Python

There are situations where you can't use the (quite convincing) with... for... structure. In that case, do the following:

line = self.fo.readline()
if len(line) != 0:
     if 'str' in line:
         break

This will work because the the readline() leaves a trailing newline character, where as EOF is just an empty string.

Solution 4 - Python

You can stop the 2-line separation in the output by using

    with open('t.ini') as f:
       for line in f:
           print line.strip()
           if 'str' in line:
              break

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionProg1020View Question on Stackoverflow
Solution 1 - PythonAshwini ChaudharyView Answer on Stackoverflow
Solution 2 - PythonSukrit KalraView Answer on Stackoverflow
Solution 3 - PythonDamian VogelView Answer on Stackoverflow
Solution 4 - PythonChrisView Answer on Stackoverflow