如何在Python中读取文件的最后一行?

2024-06-12 18:19:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个要求

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

第二项要求-

这是我的示例文件

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

我想从这个文件中读取内容,即<context:property-placeholder location= .之后的filename.txt,并想将该值赋给python中的一个变量


Tags: 文件nametxt示例内容demoservicecontext
3条回答

为什么不读取所有行并将最后一行存储到变量中

with open('filename.txt', 'r') as f:
    last_line = f.readlines()[-1]

在具有tail命令的系统上,可以使用tail,对于大文件,这将使您无需读取整个文件

from subprocess import Popen, PIPE
f = 'yourfilename.txt'
# Get the last line from the file
p = Popen(['tail','-1',f],shell=False, stderr=PIPE, stdout=PIPE)
res,err = p.communicate()
if err:
    print (err.decode())
else:
    # Use split to get the part of the line that you require
    res = res.decode().split('location="')[1].strip().split('"')[0]
    print (res)

注意:decode()命令仅适用于python3

res = res.split('location="')[1].strip().split('"')[0]

将为python2.x工作

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

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

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

import os

with open('filename.txt', 'rb') as f:
    try:  # catch OSError in case of a one line file 
        f.seek(-2, os.SEEK_END)
        while f.read(1) != b'\n':
            f.seek(-2, os.SEEK_CUR)
    except OSError:
        f.seek(0)
    last_line = f.readline().decode()

请注意,文件必须以二进制模式打开,否则,it will be impossible to seek from the end

相关问题 更多 >