打印到文件的倒数第二行 [英] Printing to the penultimate line of a file

查看:96
本文介绍了打印到文件的倒数第二行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种简单的方法可以到达打开文件的倒数第二行. f.seek给我带来了无尽的麻烦.我可以很容易地到达最后一行,但是我不知道如何到达最后一行.

I am wondering if there is a simple way to get to the penultimate line of an open file. f.seek is giving me no end of trouble. I can easily get to the final line, but I can't figure out how to get to the line above that.

推荐答案

假设文件不是太大,并且内存不是问题

Assuming the file isn't too big and memory isn't a concern

open('file.txt').readlines()[-2]

这篇关于打印到文件的倒数第二行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆