2014-03-26 21 views
0

這裏是我的代碼:如何使自動化作家附加線在Python

b = 1 
a = "line" 
f = open("test.txt", "rb+") 
if a + " " + str(b) in f.read(): 
     f.write(a + " " + str(b + 1) + "\n") 
else: 
     f.write(a + " " + str(b) + "\n") 
f.close() 

現在印刷線1條,然後第2行,但我怎麼能做出這種閱讀是什麼最後的「行x」並打印出行x + 1?

例如:

的test.txt將具有 線1 線2 線3 線4

和我的代碼將追加線路5中的端部。

我在想也許某種「找到遺言」類的代碼?

我該怎麼做?

回答

0

如果你肯定知道每一行的格式爲「字編號」,那麼你可以使用:

f = open("test.txt", "rb+") 
# Set l to be the last line 
for l in f: 
    pass 
# Get the number from the last word in the line 
num = int(l.split()[-1])) 
f.write("line %d\n"%num) 
f.close() 

如果每行的格式可以改變,你還需要處理提取號碼,re威力有用。

import re 
f = open("test.txt", "rb+") 
# Set l to be the last line 
for l in f: 
    pass 
# Get the numbers in the line 
numstrings = re.findall('(\d+)', l) 
# Handle no numbers 
if len(numstrings) == 0: 
    num = 0 
else: 
    num = int(numstrings[0]) 
f.write("line %d\n"%num) 
f.close() 

你可以找到讓最後一行的更有效的方法這裏提到What is the most efficient way to get first and last line of a text file?