如何在Python中读取文件的最后一行? [英] How to read the last line of a file in Python?

查看:255
本文介绍了如何在Python中读取文件的最后一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个要求.

首要要求-我想读取文件的最后一行,并将最后一个值分配给python中的变量.

First Requirement-I want to read the last line of a file and assign the last value to a variable in python.

第二项要求-

这是我的示例文件.

<serviceNameame="demo" wsdlUrl="demo.wsdl" serviceName="demo"/>
<context:property-placeholder location="filename.txt"/>

我要从此文件中读取 filename.txt 内容,该内容将位于< context:property-placeholder location =.之后.并希望分配该内容.值转换为python中的变量.

From this file I want to read the content i.e filename.txt which will be after <context:property-placeholder location= ..And want to assign that value to a variable in python.

推荐答案

一种简单的解决方案,不需要将整个文件存储在内存中(例如,使用 file.readlines()或同等功能)构造):

A simple solution, which doesn't require storing the entire file in memory (e.g with file.readlines() or an equivalent construct):

with open('filename.txt') as f:
    for line in f:
        pass
    last_line = line

对于大文件,查找文件末尾并向后移动以找到换行符会更有效,例如:

For large files it would be more efficient to seek to the end of the file, and move backwards to find a newline, e.g.:

import os

with open('filename.txt', 'rb') as f:
    f.seek(-2, os.SEEK_END)
    while f.read(1) != b'\n':
        f.seek(-2, os.SEEK_CUR)
    last_line = f.readline().decode()

请注意,该文件必须以二进制模式打开,否则,将无法从头开始查找

Note that the file has to be opened in binary mode, otherwise, it will be impossible to seek from the end.

这篇关于如何在Python中读取文件的最后一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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