Python: read all text file lines in loop

前端 未结 4 886
予麋鹿
予麋鹿 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 09:47

    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.

提交回复
热议问题