[英]Printing to the penultimate line of a file
我想知道是否有一種簡單的方法可以到達打開文件的倒數第二行。 f.seek沒有給我帶來麻煩。 我可以輕松到達最后一行,但是我不知道如何到達最后一行。
假設文件不是太大,並且內存不是問題
open('file.txt').readlines()[-2]
您可以從文件末尾查找並計算遇到的換行符的數目,只要您點擊第二個'\\n'
停止點並調用readline()
:
with open('foo.txt') as f:
end_count = 0
n = -1
while end_count != 2:
f.seek(n, 2)
if f.read(1) == '\n':
end_count += 1
n -= 1
print repr(f.readline())
對於像這樣的文件:
first line
second line
third line
fourth line
I want this line
last line
輸出將是:
'I want this line\n'
在大多數系統上,文件是一個單個的長字節串(某些系統具有派生,擴展或記錄),因此將行的概念推向了更高的層次。 事情變得更加復雜,行尾在所有平台上看起來都不一樣。 這意味着您必須閱讀這些行以識別它們,特別是對於文本文件,您只能將seek()到使用tell()找到的位置。
如果我們只是在閱讀倒數第二行,那很簡單:
alllines=fileobject.readlines()
penultimateline=alllines[-2]
這種方法將整個文件加載到內存中。 如果我們要替換文件的末尾(從倒數第二行開始),事情會變得更加棘手:
pen,last = 0,0
while True:
last,pen = fileobject.tell(), last
line = fileobject.readline()
if not line:
break
# back up to the penultimate line
fileobject.seek(pen) # Note: seek is *required* to switch read/write
fileobject.truncate()
fileobject.write("Ate last two lines, this is a new line.\n")
如果您只是想以任意順序讀取行,則行緩存可能會有所幫助。
每一個都掃描整個文件。 諸如tail之類的工具可能會進行另一項優化:讀取文件末尾的數據,直到找到足夠的換行符來標識所需的行。 由於查找僅在二進制模式下可預測地起作用,而行解析僅在文本模式下可預測地起作用,因此這變得更加復雜。 反過來,這意味着我們猜測文件由lineep分隔可能是錯誤的; Python的通用換行符支持僅在文本模式下運行。
backsearch=0
lines=[]
while len(lines)<=2:
backsearch+=200
fileobject.seek(-backsearch, 2)
if fileobject.tell()==0:
break # ran out of file while scanning backwards
lines=fileobject.read().split(os.linesep)
fileobject.seek(-backsearch, 2)
# Now repeat the earlier method, knowing you're only processing
# the final part of the file.
def penultimate(file_path)
return open(file_path).read().splitlines()[len(open(file_path).read().splitlines()) - 2]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.