我怎么能用python读入文本文件的最后一行?{/ 1}?
print
答案 0 :(得分:11)
一种选择是使用file.readlines()
:
f1 = open(inputFile, "r")
last_line = f1.readlines()[-1]
f1.close()
如果您之后不需要该文件,建议您使用with
使用上下文,以便文件在以下后自动关闭:
with open(inputFile, "r") as f1:
last_line = f1.readlines()[-1]
答案 1 :(得分:7)
您是否需要通过不立即将所有行读入内存来提高效率?相反,您可以迭代文件对象。
with open(inputfile, "r") as f:
for line in f: pass
print line #this is the last line of the file
答案 2 :(得分:4)
如果你能负担得起在内存中读取整个文件(如果文件大小远远小于总内存),你可以使用其他一个答案中提到的readlines()方法,但是如果文件大小很大,最好的方法是:
fi=open(inputFile, 'r')
lastline = ""
for line in fi:
lastline = line
print lastline
答案 3 :(得分:2)
您可以使用csv.reader()
将文件作为列表读取并打印最后一行。
缺点:此方法分配一个新变量(对于非常大的文件,不是理想的内存保护程序)。
优点:列表查找需要O(1)时间,如果您想要修改inputFile以及读取最后一行,则可以轻松操作列表。
import csv
lis = list(csv.reader(open(inputFile)))
print lis[-1] # prints final line as a list of strings
答案 4 :(得分:0)
这可能会对您有所帮助。
class FileRead(object):
def __init__(self, file_to_read=None,file_open_mode=None,stream_size=100):
super(FileRead, self).__init__()
self.file_to_read = file_to_read
self.file_to_write='test.txt'
self.file_mode=file_open_mode
self.stream_size=stream_size
def file_read(self):
try:
with open(self.file_to_read,self.file_mode) as file_context:
contents=file_context.read(self.stream_size)
while len(contents)>0:
yield contents
contents=file_context.read(self.stream_size)
except Exception as e:
if type(e).__name__=='IOError':
output="You have a file input/output error {}".format(e.args[1])
raise Exception (output)
else:
output="You have a file error {} {} ".format(file_context.name,e.args)
raise Exception (output)
b=FileRead("read.txt",'r')
contents=b.file_read()
lastline = ""
for content in contents:
# print '-------'
lastline = content
print lastline
答案 5 :(得分:0)
如果您在乎记忆,这应该会对您有所帮助。
last_line = ''
with open(inputfile, "r") as f:
f.seek(-2, os.SEEK_END) # -2 because last character is likely \n
cur_char = f.read(1)
while cur_char != '\n':
last_line = cur_char + last_line
f.seek(-2, os.SEEK_CUR)
cur_char = f.read(1)
print last_line
答案 6 :(得分:0)
with open("file.txt") as file:
lines = file.readlines()
print(lines[-1])
with open("file.txt") as file:
for line in file:
pass
print(line)
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())