[英]Python: read all text file lines in loop
I want to read huge text file line by line (and stop if a line with "str" found).我想逐行读取巨大的文本文件(如果找到带有“str”的行则停止)。 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
There's no need to check for EOF in python, simply do:无需在 python 中检查 EOF,只需执行以下操作:
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 : 为什么with
声明:
It is good practice to use the
with
keyword when dealing with file objects.在处理文件对象时使用with
关键字是一种很好的做法。 This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way.这样做的好处是文件在其套件完成后会被正确关闭,即使在途中引发异常也是如此。
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). Python 会自动检查文件结尾并为您关闭文件(使用with
语法)。
with open('fileName', 'r') as f:
for line in f:
if 'str' in line:
break
There are situations where you can't use the (quite convincing) with... for...
structure.在某些情况下,您不能使用(非常令人信服) with... for...
结构。 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.这将起作用,因为readline()
留下一个尾随换行符,而 EOF 只是一个空字符串。
You can stop the 2-line separation in the output by using您可以使用以下命令停止输出中的 2 行分隔
with open('t.ini') as f:
for line in f:
print line.strip()
if 'str' in line:
break
The simplest way to read a file one line at a time is this:一次读取一行文件的最简单方法是:
for line in open('fileName'):
if 'str' in line:
break
No need for a with-statement or explicit close.不需要 with 语句或显式关闭。 Notice no variable 'f' that refers to the file.注意没有引用文件的变量“f”。 In this case python assigns the result of the open() to a hidden, temporary variable.在这种情况下,python 将 open() 的结果分配给隐藏的临时变量。 When the for loop ends (no matter how -- end-of-file, break or exception), the temporary variable goes out of scope and is deleted;当for循环结束时(不管怎样--end-of-file、break或exception),临时变量从scope出来并被删除; its destructor will then close the file.然后它的析构函数将关闭该文件。
This works as long as you don't need to explicitly access the file in the loop, ie, no need for seek, flush, or similar.只要您不需要在循环中显式访问文件,即不需要查找、刷新或类似操作,这就会起作用。 Should also note that this relies on python using a reference counting garbage collector, which deletes an object as soon as its reference count goes to zero.还应该注意,这依赖于 python 使用引用计数垃圾收集器,一旦 object 的引用计数变为零,它就会删除它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.