我怎么能用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)
你是否需要通过不立即将所有行读入内存来提高效率?相反,您可以迭代文件对象.
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)
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)