简体   繁体   English

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

[英]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.

相关问题 读取从文本文件到字典python的所有行 - Read all lines from a text file to dictionary python Python-将多行文本文件读入列表 - Python - read a text file with multiple lines into a list python - 从特定文本行读取文件 - python - Read file from and to specific lines of text 在文本文件的所有行中搜索字符串:Python - searching for strings in all lines of a text file: Python 所有Python文件行都在Sublime Text 2中突出显示 - All lines of Python file are highlighted in Sublime Text 2 Python:读取文本文件的For循环未对所有文本文件记录正确执行 - Python : For loop to read a text file is not executing properly for all text file records 计算文本文件的行数并显示读取的行百分比(Python) - Count lines of a text file and show percentage of lines read (Python) Python - 如何从文本文件中读取多行作为字符串并删除所有编码? - Python - How to read multiple lines from text file as a string and remove all encoding? Python脚本循环遍历目录中的所有文件文本…如果该文件的行开头为1,则删除任何脚本 - Python script to loop through all files text in directory… delete any if that's file has lines start by 1 如何在 python 3.8 中的文本文件的所有行中循环“for”循环? - How do I make the “for” loop cycle through all lines of a text file in python 3.8?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM