Python:循环读取所有文本文件行

Pro*_*020 49 python file

我想逐行读取大文本文件(如果找到带有"str"的行,则停止).如果到达文件结尾怎么检查?

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
Run Code Online (Sandbox Code Playgroud)

Ash*_*ary 110

没有必要在python中检查EOF,只需:

with open('t.ini') as f:
   for line in f:
       print line
       if 'str' in line:
          break
Run Code Online (Sandbox Code Playgroud)

为什么with声明:

with在处理文件对象时,最好使用关键字.这样做的好处是文件在套件完成后正确关闭,即使在途中引发了异常.


Suk*_*lra 8

只需遍历文件中的每一行.Python会自动检查文件结尾并为您关闭文件(使用with语法).

with open('fileName', 'r') as f:
    for line in f:
       if 'str' in line:
           break
Run Code Online (Sandbox Code Playgroud)


Dam*_*gel 5

在某些情况下,您无法使用(非常有说服力的)with... for...结构。在这种情况下,请执行以下操作:

line = self.fo.readline()
if len(line) != 0:
     if 'str' in line:
         break
Run Code Online (Sandbox Code Playgroud)

这将起作用,因为它readline()留下了一个尾随换行符,而 EOF 只是一个空字符串。