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

Mic*_* IV 11 python

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

 f = open("myfile.txt")
 for line in f:
    if line is lastline:
       #do smth
Run Code Online (Sandbox Code Playgroud)

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

对不起,如果我的问题是多余的,因为我没有在SO上找到答案

Pad*_*ham 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
Run Code Online (Sandbox Code Playgroud)

如果你想要第二行使用 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
Run Code Online (Sandbox Code Playgroud)

  • 你的解决方案很糟糕,因为它会将整个文件加载到内存中,对于足够大的文件,它只是"segfault". (3认同)
  • 你是对的,OP 说“我正在用 Python 逐行读取文件”,而不是一次读取每一行。 (3认同)

tom*_*sen 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)
Run Code Online (Sandbox Code Playgroud)


ins*_*get 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
Run Code Online (Sandbox Code Playgroud)