簡體   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