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
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.
1 2 3 4 5 |
fruitsStr = ' Apple \n Orange \n Banana \n Pineapple' with open('fruits.txt','x') as file: file.write(fruitsStr) |
Here is content of fruits.txt.
$ cat fruits.txt
Apple
Orange
Banana
Pineapple
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
1 2 3 4 5 |
fruitsStr = ' Mango \n Grapes' with open('fruits.txt','w') as file: file.write(fruitsStr) |
$ cat fruits.txt
Mango
Grapes
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.
1 2 3 4 5 |
fruitsStr = '\n Lichy \n Pomegranate' with open('fruits.txt','a') as file: file.write(fruitsStr) |
$ cat fruits.txt
Mango
Grapes
Lichy
Pomegranate
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.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.