Python write to text file

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.

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.

$ cat 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

$ cat 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.

$ cat fruits.txt
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?

Leave a Reply

Your email address will not be published. Required fields are marked *