繁体   English   中英

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

[英]How to read the last line of a file in Python?

我有两个要求。

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

第二个要求-

这是我的示例文件。

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

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

一个简单的解决方案,不需要将整个文件存储在内存中(例如使用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:
    f.seek(-2, os.SEEK_END)
    while f.read(1) != b'\n':
        f.seek(-2, os.SEEK_CUR)
    last_line = f.readline().decode()

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

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

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

他不只是问如何读取文件中的行,或者如何将最后一行读入变量。 他还询问如何从最后一行解析出包含目标值的子字符串。

这是一种方法。 这是最短的路吗? 不,但是如果您不知道如何对字符串进行切片,您应该从学习这里使用的每个内置函数开始。 这段代码会得到你想要的:

# Open the file
myfile = open("filename.txt", "r")
# Read all the lines into a List
lst = list(myfile.readlines())
# Close the file
myfile.close()
# Get just the last line
lastline = lst[len(lst)-1]
# Locate the start of the label you want, 
# and set the start position at the end 
# of the label:
intStart = lastline.find('location="') + 10
# snip off a substring from the 
# target value to the end (this is called a slice):
sub = lastline[intStart:]
# Your ending marker is now the 
# ending quote (") that is located 
# at the end of your target value.
# Get it's index.
intEnd = sub.find('"')
# Finally, grab the value, using 
# another slice operation.
finalvalue = sub[0:intEnd]
print finalvalue

打印命令输出应如下所示:

filename.txt

此处涵盖的主题:

  • 读取文本文件
  • 从内容中创建行的 Python 列表,以便使用从零开始的索引len(List) -1轻松获取最后一行。
  • 使用find获取字符串中字符串的索引位置
  • 使用slice获取子串

所有这些主题都在 Python 文档中 - 这里没有任何额外内容,并且无需导入即可使用此处使用的内置函数。

干杯,
-=卡梅伦

在具有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

做尺寸检查

如果 os.path.getsize(file) > 200:

  with open(fname, 'rb') as myfile:
  myfile.seek(-200, 2)
  line = myfile.readlines()[-1].decode("utf-8")

在 python3 中需要以二进制模式打开(不能进行非零的端相对查找)。 myfile.seek(-200, 2) 将当前文件指针设置在距文件末尾 200 个字符处(2)然后它将读取行,返回最后并对其进行解码

概括为从第 N 行到最后一行

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

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

您可以阅读和编辑所有行,执行以下操作:

file = open('your_file.txt', 'r')
read_file = file.readlines()
file.close()

file1 = open('your_file.txt', 'w')

var = 'filename.txt'

for lec in range(len(read_file)):
    if lec == 1:
        file1.write('<context:property-placeholder location="%s"/>' % var)
    else:
        file1.write(read_file[lec])
file1.close()

来自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) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM