打印最后一行文件用Python读入

pHo*_*pec 4 python

我怎么能用printpython读入文本文件的最后一行?

fi=open(inputFile,"r")
for line in fi:
    #go to last line and print it
Run Code Online (Sandbox Code Playgroud)

Rus*_*hal 11

一种选择是使用file.readlines():

f1 = open(inputFile, "r")
last_line = f1.readlines()[-1]
f1.close()
Run Code Online (Sandbox Code Playgroud)

但是,如果之后不需要该文件,建议使用上下文with,以便在以下情况下自动关闭该文件:

with open(inputFile, "r") as f1:
    last_line = f1.readlines()[-1]
Run Code Online (Sandbox Code Playgroud)

  • 这不应该用于大文件,因为它完全读取它们,并且除了最后一行之外只丢弃所有文件. (2认同)

gni*_*las 7

你是否需要通过不立即将所有行读入内存来提高效率?相反,您可以迭代文件对象.

with open(inputfile, "r") as f:
    for line in f: pass
    print line #this is the last line of the file
Run Code Online (Sandbox Code Playgroud)


kaf*_*ran 7

读取文件最后一行的三种方法:

  • 对于小文件,将整个文件读入内存

with open("file.txt") as file:            
    lines = file.readlines()
print(lines[-1])
Run Code Online (Sandbox Code Playgroud)
  • 对于大文件,逐行读取并打印最后一行

with open("file.txt") as file:
    for line in file:
        pass
print(line)
Run Code Online (Sandbox Code Playgroud)
  • 为了有效的方法,直接转到最后一行

import os

with open("file.txt", "rb") as file:
    # Go to the end of the file before the last break-line
    file.seek(-2, os.SEEK_END) 
    # Keep reading backward until you find the next break-line
    while file.read(1) != b'\n':
        file.seek(-2, os.SEEK_CUR) 
    print(file.readline().decode())
Run Code Online (Sandbox Code Playgroud)