Python program to append text to a file

Python program to append text to a file:

We can use open() function to open a file for reading/writing purpose. This function takes the file path as the first parameter and the mode of operation as the second parameter.

For appending text to a file, we can use the append mode which is defined by the ‘a’ character.

If we use append mode, it will always start the writing at the end of the file, i.e. it appends the data.

In this post, we will learn how to use append with different use cases.

Example 1: Using open() and ‘a’:

Let’s take a look at the below example:

file_path = 'readme.txt'
f = open(file_path, 'a')

f.write('Adding new line at the end')
f.close()

This program will write the line at the end of the file readme.txt, which is in the same folder where this python program file exists.

If the file has below text:

Hello World !!

It will become:

Hello World !!Adding new line at the end

Adding a new line while appending:

We can add one new line by adding \n at the start of the line:

file_path = 'readme.txt'
f = open(file_path, 'a')

f.write('\nAdding new line at the end')
f.close()

It will add the line in the next line.

Hello World !!
Adding new line at the end

Opening the file in byte mode:

By default, it opens the file in text mode. But, we can also open it in byte mode by using ab as the mode for opening.

file_path = 'readme.txt'
f = open(file_path, 'ab')

b_str = b'hello world'
f.write(b_str)
f.close()

If we use at, it will open the file in text mode, which is same as a.

Using ‘with open’:

We can also use ‘with open’ to open a file:

file_path = 'readme.txt'
with open(file_path, 'ab') as f:
    b_str = b'hello world'
    f.write(b_str)
    f.close()

You might also like: