4

So my code looks like this .... but I want to add data always to the end of the document how would I do this

try:
    f = open("file.txt", "w")
    try:
        f.write('blah') # Write a string to a file
        f.writelines(lines) # Write a sequence of strings to a file
    finally:
        f.close()
except IOError:
    pass

2 Answers 2

15

Open the file using 'a' (append) instead of 'w' (write, truncate)

Besides that, you can do the following isntead of the try..finally block:

with open('file.txt', 'a') as f:
    f.write('blah')
    f.writelines(lines)

The with block automatically takes care about closing the file at the end of the block.

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

Comments

4

open the file with "a" instead of "w"

1 Comment

Reopen? If he opens it with w before, it'll already be empty.

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.