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?

7
  • Yes, just open the file like this with open('textfile.txt', 'a') as tf: and then whatever you .write to it will be appended at the end of the file.
    – Stam Kaly
    Commented Jul 19, 2017 at 18:11
  • @downshift I already did. Commented Jul 19, 2017 at 18:15
  • Oh ok, I must have misunderstood, since it showed your link differently. thanks. Commented Jul 19, 2017 at 18:16
  • @downshift I think you need more rep to close vote Commented Jul 19, 2017 at 18:17
  • I do not want to close a vote. I want the Flag to merge same votes. Perhaps I completely do not understand how identical Flag requests work. I expected to see the number next to my flag increment when another user Flags with the same duplicate link. Commented Jul 19, 2017 at 18:18

1 Answer 1

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.