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

2024-03-28 08:58:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我想逐行读取巨大的文本文件(如果找到“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

Tags: 文件tologthatischeck结尾not
3条回答

在某些情况下,您不能使用(非常令人信服的)with... for...结构。在这种情况下,请执行以下操作:

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

这将起作用,因为readline()留下一个尾随的换行符,其中as EOF只是一个空字符串。

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

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

不需要在python中检查EOF,只需执行以下操作:

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

Why the ^{} 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.

相关问题 更多 >