In this post, we will see how to write to a text file.
There are multiple modes in which you can write to text
file.
Table of Contents [hide]
Create txt file(‘x’)
It will open the file in 'X'
mode which will create new file and return error in case file already exists.
Here is content of fruits.txt.
Apple
Orange
Banana
Pineapple
Write to txt file(‘w’)
It will open the file in 'w'
mode which will write to file and will override the content of fruits.txt
Mango
Grapes
As you can see, it has overridden content of file which we have read in 'w'
mode.
Append to txt file(‘a’)
It will open the file in ‘a’ mode which will append to the file.
Mango
Grapes
Lichy
Pomegranate
As you can see Lichy and Pomegranate were appended to the content of fruits.txt
.
That’s all about Python write to text file.