5

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?

user3341402
  • 85
  • 1
  • 1
  • 2

4 Answers4

5

open the file in append mode

open(filename, 'a')
ch3ka
  • 11,242
  • 4
  • 29
  • 25
4

Just use append mode:

with open('something.txt', 'a') as f:
    f.write('text to be appended')

Documentation can be found here.

tckmn
  • 55,458
  • 23
  • 108
  • 154
2

Open your file with something like

f = open('myfile.log', 'a')

you can also check documentation for more alternatives

frlan
  • 6,698
  • 3
  • 26
  • 70
1

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.

Minelr G
  • 69
  • 2
  • 11