3

I'm attempting to make a function that writes a string to the last line in a file. However, what I currently have (below) only writes to the first line. So if I call the function more than once, it simply overwrites the first line. I'd like it to instead write the string to a new line; how would I go about this?

Snippet :

def write (self, string) :
    # self.Dir is a txt file
    self.File = file(self.Dir, 'w')
    self.File.write(string)

1 Answer 1

17

Open the file in append mode ('a' instead of 'w'). Opening in 'w' mode truncates your file (you're now writing into an empty file)

Sign up to request clarification or add additional context in comments.

1 Comment

And remember to put in a newline character '\n' after the last string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.