这是我的代码:
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 :(得分: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?