Python Write Text File

Python provides built-in functions to perform file operations, such as creating, reading, and writing files. There are mainly two types of files that Python can handle, normal text files and binary files. In this tutorial, we will look at how to write content into text files in Python.

Steps on How to write to a File in Python

In order to write to a text file in Python, you need to follow the below steps.

Step 1: The file needs to be opened for writing using the open() method and pass a file path to the function.

Step 2: The next step is to write to file, and this can be achieved using several built-in methods such as write(), writelines().

Step 3: Once the write operation is performed, the text file must be closed using the close() function.

Now that we have seen the steps to write to a text file let’s understand each of these methods before getting into examples.

Python open() function 

The open() function opens the file if possible and returns the corresponding file object.

Syntax – open(file, mode=’w’, buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

The open() function has a lot of parameters. Let’s take a look at the necessary params for writing to a text file. It opens the file in a specified mode and returns a file object.

Parameters 

  • file – path like object which represents the file path
  • mode (Optional) – The mode is an optional parameter. It’s a string that specifies the mode in which you want to open the file.
ModeDescription
'r'Open a file for read mode (default if mode is not specified)
'w'Open a file for writing. Python will create a new file if does not exist or truncates a file content if file exists
'x'Open a file for exclusive creation.
'a'Open a file for appending the text. Creates a new file if file does not exist.
't'Open a file in text mode. (default)
'b'Open a file in binary mode.
'+'Open a file for updating (reading and writing)

Example 

file = open('C:\hello.txt','w')

Methods for Writing to a text file in Python

There are two ways to write data into a text file.

  1. write()The write() function will write a line to a text file. It inserts a single line in the text file.
  2. writelines(): The writelines() function will write multiple string lines at once to a text file. The writelines() method accepts an iterable object such as list, set, tuple, etc. 

Python close() function

The file will remain open until you close the file using the close() function. It is a must and best practice to perform this operation after writing the data into the file as it frees up the memory space acquired by that file. Otherwise, it may cause an unhandled exception. 

We can use the with statement, which helps to close the file once the write operation is performed. We don’t have to specify any explicit close method everytime.

Examples for Writing to Text file in Python 

Example 1 – Write a line to a text file using the write() function

Let’s look at writing a line into a text file using the write() method. We will use the with statement, which helps to close the file once the write operation is performed. We don’t have to specify any explicit close method.

# Program to write to text file using write() function
with  open("python.txt", "w") as file:
	content = "Hello, Welcome to Python Tutorial !! \n"
	file.write(content)
	file.close()


# Program to read the entire file (absolute path) using read() function
with open("C:/Projects/Tryouts/python.txt", "r") as file:
	content = file.read()
	print(content)
	file.close()

Output

Hello, Welcome to Python Tutorial !! 

Example 2 – Append a line to a text file using the write() function

If you want to append the line to the existing text file, you need to open the file in the append mode first and perform the write() operation, as shown below.

# Program to append to text file using write() function
with  open("python.txt", "a") as file:
	content = "Append the content at the end \n"
	file.write(content)
	file.close()


# Program to read the entire file (absolute path) using read() function
with open("C:/Projects/Tryouts/python.txt", "r") as file:
	content = file.read()
	print(content)
	file.close()

Output

Hello, Welcome to Python Tutorial !! 
Append the content at the end

Example 3 – Write a list to a file using the writelines() function

Let’s look at writing multiple lines into a text file using the writelines() method. The writelines() method accepts an iterable object such as list, set, tuple, etc. In the below example let’s see how to write a list to a file in Python

Syntax of writelines()

file.writelines(list)

Parameters

list – The list of texts or byte objects that will be inserted. It can be a list, tuple, set of strings, etc.

# Program to write multiple lines to text file using writelines() function
with open("python.txt", "w") as file:
    content = ["Hello\n", "Welcome to Python Tutorial\n", "Cheers \n" ]
    file.writelines(content)
    file.close()

# Program to read the entire file (absolute path) using read() function
with open("C:/Projects/Tryouts/python.txt", "r") as file:
    content = file.read()
    print(content)
    file.close()

Output

Hello
Welcome to Python Tutorial
Cheers

Example 4 – Append multiple lines to a text file using the writelines() function

If you want to append multiple lines to the existing text file, you need to open the file in the append mode first and perform the writelines() operation, as shown below.

# Program to append to text file using writelines() function
with open("python.txt", "a") as file:
    content = ["Appending the content\n", "Python\n" ]
    file.writelines(content)
    file.close()

# Program to read the entire file (absolute path) using read() function
with open("C:/Projects/Tryouts/python.txt", "r") as file:
    content = file.read()
    print(content)
    file.close()

Output

Hello
Welcome to Python Tutorial
Cheers
Appending the content
Python
Leave a Reply

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

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like