Python: read all text file lines in loop

前端 未结 4 888
予麋鹿
予麋鹿 2020-11-28 08:56

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\')
         


        
4条回答
  •  悲哀的现实
    2020-11-28 09:43

    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.

提交回复
热议问题