In one of my previous post that can be found here, I have discussed about a simple program in python that will allow us to write a text to a file. But the problem with this approach is that each time you write a new text to a file, the previous text is overridden by the new one. So your previous text is lost. This is not a good approach for adding new text content to a file. Python has another access mode for file handling i.e. append mode that will write a new content to an existing file without ever having to modify the original one. This simple program below demonstrates this concept.
First I will show you how write mode will modify the existing content in the file. You can see the content inside Written Text.txt
:
Now, I will execute this simple program in write mode.
Now if you open your original Written Text.txt
file, you can now see your content is being replaced by the new one.
Now, I will use append mode and this will add our new text to an existing one.
f = open("Written Text.txt", "a")
content = ["\nThis text was written through append mode. \n", "Append mode will add new content to the existing"
"file. \n", ""]
f.writelines(content)
f.close()
We should just add "a" as an extra parameter to open function for append mode. Lets run this code.
You can now see these two lines have been added to the original one.