2011-07-01 27 views
-3

我有.dat文件的樣子:Python的命令來獲得最後一部分文件

STEP1 A1 B1 A2 B2 A3 B3

STEP2 A4 B4 A5 B5 。 。 。 STEPn an bn am bm

每一步都有兩列(a和b)。我需要一張紙,看起來最後一步,並給我「一個」和「上午」

謝謝你的幫助!

+0

你到目前爲止嘗試過什麼?具體來說,你有什麼問題? – RHSeeger

+0

該網站的想法是提出關於編程的問題,而不是要求別人爲你做你的編程。如果您對此腳本有疑問,請更具體地瞭解它。 –

回答

0

假設你所有的步驟都是在單獨的行和該文件的最後一行是你的最後一步

f = open("data.dat", "r") 
lines = f.readlines() 
last_line = lines[-1] 
step, an, bn, am, bm = last_line.split() 
+0

這不必要地使用內存('f.readlines()'部分,它將整個文件加載到內存中)。 – EOL

+1

是的,我同意。我喜歡你的解決方案。 – bear24rw

+0

謝謝,很高興你能感激它。 :) – EOL

1

東西有效,即使有很長的文件的工作(使用幾乎沒有記憶):

with open("data.dat") as f: # File automatically closed 
    for line in f: # Goes through all the line (no need to store them) 
     pass 
step, an, bn, am, bm = line.split() # Splits the last line read (on spaces) 

如果您需要轉換數值,int(an)float(an)的工作。

相關問題