I'm currently working on a bit of code that requires me to keep records of the outcome. However, at the minute, the code I'm using only overwrites the document, rather than adding on. What can I write to add something to the end of a text document?
-
This question is [too broad](http://stackoverflow.com/help/on-topic). – Jørgen R Dec 15 '14 at 15:08
-
You should show us the code you uses to write in your file. – Benoît Latinier Dec 15 '14 at 15:08
-
Sorry about the original broadness, and I found an answer on the website too. Thanks for the help anyway. – user3341402 Dec 15 '14 at 16:19
4 Answers
Just use append mode:
with open('something.txt', 'a') as f:
f.write('text to be appended')
Documentation can be found here.

- 57,719
- 27
- 114
- 156
Open your file with something like
f = open('myfile.log', 'a')
you can also check documentation for more alternatives

- 6,950
- 3
- 31
- 72
Everyone is correct about using append mode for opening files that you want to add to, not overwrite. Here are some links that helped me learn a bit more about opening and editing files in python.
http://www.tutorialspoint.com/python/python_files_io.htm
https://docs.python.org/2/tutorial/inputoutput.html
I am not sure if it's written in your code, but it is always a good idea to .close() the file when you are done writing to it. If it's not a terribly huge file it doesn't hurt to make sure what you appended is actually in the file. So it would be something like:
with open('file.txt', 'a') as f:
f.write("Some string\n")
with open('file.txt', "r") as f:
for line in f:
if "Some string" in line:
f.close()
return True
return False
There are more concise ways to write this, but I wanted to try and make it as accessible to everyone as I could. Also note checking for the string I am assuming that exact string does not repeat.

- 69
- 2
- 11