How to write text files in Python 3?

Problem:

A very common development task is to work with text files, specifically create the file as well as read and write data into it.

Solution:

Python delivers built-in functions to create and manipulate text files. We will also show you that we are able to append text after the file is created. Let’s look into a couple of examples.

Creating a file in Python:

To create a file in python, we can use the open(“filename”, “accessmode”) function. The below code will create a file named mydocument.txt with the access of Write permission. This file will get created under the folder where the code is getting executed. 

Code:

f = open("mydocument.txt", "w")
f.write("This text is written in python")
f.close

Create a file under a different path:

To create a file under a different path, we will have to make a slight change in the open(r”filepath&name”, “accessmode”) function. The before the file path is a raw string. It will make sure to read all without any special characters. We will need to make sure that the provided directory is created. Let’s see it with an example.

Code:

f = open(r"C:\myfile\mydocument.txt", "w")
f.write("This text is written in python")
f.close

Append text to an existing file:

The files we created using “w” as access mode will overwrite the file with the new text if the file already existed. Hence we can use “a” helps to append. Append will insert the data after the existing data. Let’s learn it with an example.

Code:

#write
f = open(r"mydocument.txt", "w") 
f.write("This text is written in python. ")
f.close()
#read
f = open("mydocument.txt", "r")
print("New text:",f.read())
#append
f = open(r"mydocument.txt", "a")
f.write("This text is added using Append.")
f.close()
#read
f = open("mydocument.txt", "r")
print("Append:",f.read())

Output:

New text: This text is written in python.
Append: This text is written in python. This text is added using Append.