有沒有 優雅的 python 倒著一行一行讀大檔案的例子

時間 2021-06-04 21:48:15

1樓:Justin Z

file_read_backwards - file_read_backwards 2.0.0 documentation

乙個現成的包,安裝:

pip install file_read_backwards

官方Python 3的例子:

from file_read_backwards import FileReadBackwards

with FileReadBackwards("/tmp/file", encoding="utf-8") as frb:

# getting lines by lines starting from the last line up

for l in frbprint(l)

2樓:

unix 最好用 tail,不管是 python call shell 還是 shell pipeline python 都可以。

3樓:

#!/usr/bin/env python3import

sysimport

osimport

time

defget_size

(fname

):st=os

.stat

(fname

)returnst.

st_size

deftail_f

(fname

):buf=""

last_size=0

while

True

:new_size

=get_size

(fname)if

new_size

==last_size

:time

.sleep(1

)continue

with

open

(fname

,"r")as

f:f.

seek

(last_size)d

=buf+f

.read

()buf=''

lines=d

.splitlines

()if

notd

.endswith("

\n"):buf

=lines[-

1]lines

=lines[:-

1]forl

inlines

:yield

llast_size=f

.tell

()def

main

():forlin

tail_f

(sys

.argv[1

]):print(l

)return0if

__name__

=="__main__"

:sys

.exit

(main())

Python如何優雅地倒著讀檔案?

西瓜甜 from collections import deque with open file name r encoding utf 8 as fb dq deque fb 讀取方式一 從尾讀到頭,讀完 whiledq last row dq pop 讀取方式二 從尾讀開始讀,到指定條件後結束w...

國畫梅花有沒有不能倒著畫花朵的禁忌?

禁忌是沒有的這東西就是恨屋及烏!肖戰別說是倒著畫梅花,就是倒著寫福字,也會被起諧音梗嘲笑的!建議早日習慣,國畫界的各位也不用太擔心,所有肖戰身上發生的嘲諷其實都是在嘲諷肖戰及蝦們,不涉及一般事物。不信你們可以畫一幅倒著的梅花發微博上,會收穫 大大好厲害 以及 看看正宗國畫選手的畫,肖戰還立設計師人設...

Python有沒有乙個類似RStudio一樣的IDE?

Heaton Yu Spyder在工具欄有乙個設定layout布局的地方,可以調整為r studio的布局風格,右上是變數和歷史記錄,左下是ipython console和python console,超像的! 喜歡輕量級的編輯器Sublime Text的路過 Spyder有用過,在Ubuntu中的...