2

I am trying to get the program to automatically start at the last line of a text file when I run it and make it write on the last line. My current code is as follows:

with open('textfile.txt', 'a+') as tf
    last_line = tf.readlines()[-1]
    tf.write(linetext + '\n')`

When I run this, it says that the list index is out of range. How do I get this to automatically skip to the last line of a text file and start writing from there?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
BonsaiKaya
  • 31
  • 1
  • 4

1 Answers1

3

Use the a flag while opening the file

with open('path/to/file', 'a') as outfile:
    outfile.write("This is the new last line\n")
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241