在python中读取文件的最后一行

tec*_*chi 3 python python-2.7 python-3.x python-requests

我有两个要求.

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

第二要求 -

这是我的示例文件.

<serviceNameame="demo" wsdlUrl="demo.wsdl" serviceName="demo"/>
<context:property-placeholder location="filename.txt"/>
Run Code Online (Sandbox Code Playgroud)

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

Jaz*_*man 15

通用化读取第 N 行到最后一行

正如许多其他人所说,对于大文件,任何不查找末尾或从文件末尾开始的方法都是非常低效的。不过,最佳答案的搜索方法很棒。如果其他人正在寻找一种读取文件的第 n 行到最后一行的解决方案,这里是我写的一个。对于大型文件也非常快速和高效(网络上 7GB 文件需要不到 1 毫秒)。

def read_n_to_last_line(filename, n = 1):
    """Returns the nth before last line of a file (n=1 gives last line)"""
    num_newlines = 0
    with open(filename, 'rb') as f:
        try:
            f.seek(-2, os.SEEK_END)    
            while num_newlines < n:
                f.seek(-2, os.SEEK_CUR)
                if f.read(1) == b'\n':
                    num_newlines += 1
        except OSError:
            f.seek(0)
        last_line = f.readline().decode()
    return last_line
Run Code Online (Sandbox Code Playgroud)


小智 7

为什么你只读取所有行并将最后一行存储到变量?

f_read = open("filename.txt", "r")
last_line = f_read.readlines()[-1]
f_read.close()
Run Code Online (Sandbox Code Playgroud)

  • @LS 这以什么方式有效?如果你的文件有数百万行,你就必须读取数百万行。除了“seek”或从文件末尾开始的方法之外,任何其他方法的效率都非常低。 (12认同)

Rol*_*ony 6

在具有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)
Run Code Online (Sandbox Code Playgroud)

对于通用的whole last line

res = res.decode()
print(res)
Run Code Online (Sandbox Code Playgroud)

要调整行数,请更改tail命令。
对于最后 10 行,您将使用['tail','-10',f]

从第 N 行到末尾:['tail','-n+10000',f]
其中 10,000 是您要读取的行

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

res = res.split('location="')[1].strip().split('"')[0]
Run Code Online (Sandbox Code Playgroud)

会为python2.x


Eug*_*ash 6

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

with open('filename.txt') as f:
    for line in f:
        pass
    last_line = line
Run Code Online (Sandbox Code Playgroud)

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

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()
Run Code Online (Sandbox Code Playgroud)

  • @LS如果你在足够大的文件(例如几兆字节)上尝试它,“file.readlines()”将比简单的“for”循环慢。对于较大的文件,它也可能耗尽您的可用内存。 (2认同)
  • 这个答案是我2013年的旧答案的重复,它也有一个支持边缘情况的版本以及使用疾驰搜索的更新版本/sf/answers/1302214581/ (2认同)

Paa*_*sen 6

来自https://docs.python.org/3/library/collections.html的示例

from collections import deque

def tail(filename, n=10):
    'Return the last n lines of a file'
    with open(filename) as f:
        return deque(f, n) 
Run Code Online (Sandbox Code Playgroud)

  • 这将逐行读取整个文件。这可以节省内存,但对于大文件来说速度不会很快。 (2认同)

归档时间:

查看次数:

8347 次

最近记录:

6 年,11 月 前