使用open(),如何判断我是否在文件的最后一行?

时间:2019-06-29 22:26:23

标签: python python-3.x

我有:

with open(self.corpus_file) as infile:
    for line in infile:

如何确定line是否是infile的最后一行?

如果重要的话,这就是Python 3.6。

5 个答案:

答案 0 :(得分:4)

这是一种简单的方法:

from itertools import tee

with open(self.corpus_file) as infile:
    infile, check = tee(infile)
    try:
        next(check)
    except StopIteration:
        # file is empty
    for line in infile:
        try:
            next(check)
        except StopIteration:
            # line is the last line

如果您不必停留在循环中,则是另一种甚至更简单的方法:

with open(self.corpus_file) as infile:
    for line in infile:
        pass

# line is now the last line

答案 1 :(得分:3)

open返回的文件对象是Python中的迭代器,因此您可以在进行StopIteration来消耗next循环中的行的同时注意while

with open(self.corpus_file) as f: 
    line = None 
    while True: 
        try: 
            line = next(f) 
        except StopIteration: 
            break 

现在line应该包含最后一行。

答案 2 :(得分:3)

通常,您不想尝试在循环内部弄清楚这一点,但是,当循环退出时,您会知道已经到了尽头。如果您想在结束时做一些特别的事情(有时可能break跳出循环),则可以在else上添加for子句:

with open(filename) as file:
    for line in file:
        if not do_stuff(line):
            break
    else: # got to the end without breaking
        do_something_special_with_last_line(line)

答案 3 :(得分:3)

利用文件是迭代器的事实,可以使用以下通用配方。它与每行一起返回状态标志。基础迭代器的最后一个元素的标志为True

def is_last(iterator):
    prev = next(iterator)  # immediate StopIteration possible
    for item in iterator:
        yield False, prev
        prev = item
    yield True, prev

您会喜欢使用它

with open(...) as infile:
    for last, line in is_last(infile):
        ...

答案 4 :(得分:2)

您可以像这样使用collections.deque

from collections import deque


def read_file(filename):
    with open(filename) as infile:
        dq = deque([next(infile)], 1)
        for line in infile:
            yield dq[0]
            dq.append(line)

    # Last line of file.
    yield 'LAST LINE: ' + dq[0]


corpus_file = 'corpus_file.txt'

for line in read_file(corpus_file):
    print(line, end='')