0

Here is my Code :

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()

It prints now line 1 and then line 2, but how can i make this read what is the last "line x" and print out line x + 1?

for example:

test.txt would have line 1 line 2 line 3 line 4

and my code would append line 5 in the end.

I was thinking maybe some kind of "find last word" kind of code?

How can I do this?

tshepang
  • 12,111
  • 21
  • 91
  • 136
user3454635
  • 127
  • 1
  • 1
  • 6

1 Answers1

0

If you know for certain that every line has the format "word number" then you could use:

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()

If the format of each line can change and you also need to handle extracting numbers, re might be useful.

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()

You can find more efficient ways of getting the last line as mentioned here What is the most efficient way to get first and last line of a text file?

Community
  • 1
  • 1
jmetz
  • 12,144
  • 3
  • 30
  • 41