Python:检测文件读取中的当前行是否为最后一行

时间:2014-07-27 16:28:53

标签: python

我正在逐行读取Python中的文件,我需要知道在阅读时哪一行是最后一行,如下所示:

 f = open("myfile.txt")
 for line in f:
    if line is lastline:
       #do smth

examples我发现它涉及搜索和完整的文件读数来计算行数等。我可以检测到当前行是最后一行吗?我试着去检查" \ n"存在,但在很多情况下,最后一行后面没有反斜杠N。

很抱歉,如果我的问题是多余的,因为我在SO

上找不到答案

7 个答案:

答案 0 :(得分:7)

检查行is是否在最后一行:

with open("in.txt") as f:
    lines = f.readlines()
    last = lines[-1]
    for line in lines:
        if line is last:
            print id(line),id(last)
            # do work on lst line
        else:
            # work on other lines

如果您希望倒数第二行使用last = lines[-2]

或者简单地说:

with open("in.txt") as f:
    lines = f.readlines()
    last = lines[-1]
    for line in lines[:-1]:
        # work on all but last line
    # work on last

答案 1 :(得分:7)

import os
path = 'myfile.txt'
size = os.path.getsize(path)
with open(path) as f:
    for line in f:
        size -= len(line)
        if not size:
            print('this is the last line')
            print(line)

答案 2 :(得分:3)

secondLastLine = None
lastLine = None
with open("myfile.txt") as infile:
    secondLastLine, lastLine = infile.readline(), infile.readline()
    for line in infile:
        # do stuff
        secondLastLine = lastLine
        lastLine = line

# do stuff with secondLastLine

答案 3 :(得分:2)

您可以尝试的一件事是尝试获取下一行,并在出现异常时捕获异常,因为AFAIK python迭代器没有内置的hasNext方法。

答案 4 :(得分:2)

您可以使用itertools pairwise recipe;

with open('myfile.txt') as infile:
    a,b = itertools.tee(infile)
    next(b, None)
    pairs = zip(a,b)
    lastPair = None
    for lastPair in pairs:
        pass
secondLastLine = lastPair[0]
# do stuff with secondLastLine

答案 5 :(得分:0)

这是一个古老的问题,但是如果您想允许最后一行为空,则更好:

with open("myfile.txt") as f:
    while True:
        line = f.readline()
        # do smth
        if line[-1:] != '\n':
            # do smth with the last line
            break

或更易读(但慢一点):

with open("myfile.txt") as f:
    while True:
        line = f.readline()
        # do smth
        if not line.endswith('\n'):
            # do smth with the last line
            break

答案 6 :(得分:0)

只需检查f.readline()的输出,当文件中没有更多行时,它应该为空字符串。

阿尔贝托。