Python:循环读取所有文本文件行 [英] Python: read all text file lines in loop

查看:571
本文介绍了Python:循环读取所有文本文件行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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')
while not _is_eof(f): ## how to check that end is reached?
    s = f.readline()
    print s
    if "str" in s: break

推荐答案

无需检查python中的EOF,只需执行以下操作:

There's no need to check for EOF in python, simply do:

with open('t.ini') as f:
   for line in f:
       # For Python3, use print(line)
       print line
       if 'str' in line:
          break

为什么with语句 :

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

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.

这篇关于Python:循环读取所有文本文件行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆