Python:循环读取所有文本文件行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17949508/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: read all text file lines in loop
提问by Prog1020
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?
我想逐行读取巨大的文本文件(如果找到带有“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
采纳答案by Ashwini Chaudhary
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
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.
with
在处理文件对象时使用关键字是一种很好的做法。这样做的好处是文件在其套件完成后会被正确关闭,即使在途中引发异常也是如此。
回答by Sukrit Kalra
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
回答by Damian Vogel
There are situations where you can't use the (quite convincing) with... for...
structure. In that case, do the following:
在某些情况下,您无法使用(非常有说服力的)with... for...
结构。在这种情况下,请执行以下操作:
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 只是一个空字符串。