Append Text to a File in Python

Python offers several file access modes. One of them is “append”. This mode allows you to place the cursor at the end of the text file to insert the new lines there.

with open('D://file.txt', 'a') as f:
    f.write('First line.')

If the file doesn’t exist, it’s created and the text is written at the beginning.

If you run the code again, the code it’s not in the second line, but stays in the same.

This happened because the cursor is not moved to the new line at the end of the string. We can change that by adding the new line character (\n) to each line.

with open('D://file.txt', 'a') as f:
    f.write('First line.\n')
    f.write('Second line.\n')

The new line character moves the cursor to the next line. We also added the new line at the end of the last string. If the additional text is added in the future we want it to start from the new line.

Append text to a file only if the file exists

If the file The append file access appends text at the end of the file. If the file doesn’t exist, it creates it and sets the cursor at the beginning of the file.

If you want to use the append operation only if the file exists, you have to check the file path first.

To do it, first, you have to import the os module.

import os

file_path = 'D://file.txt'
file_exists = os.path.isfile(file_path)

if file_exists:
    with open(file_path, 'a') as f:
        f.write('First line.\n')
        f.write('Second line.\n')

This code will add both lines only if the file exists and do nothing otherwise.

The line: os.path.isfile(file_path) checks whether there is a file in the file_path. The file_exists returns True if the condition is met.

If the file exists the lines are added at the end of the file.

Append text to a file using “with”

In the previous examples, we used “with” to open a file. With this word, the file is opened and closed immediately after leaving the scope. You can check it using the “closed” property.

import os

file_path = 'D://file.txt'
file_exists = os.path.isfile(file_path)

with open(file_path, 'a') as f:
    f.write('First line.\n')
    f.write('Second line.\n')
    print(f.closed)
print(f.closed)

Two print functions print whether the file is closed or not. If it’s closed, it returns True, otherwise False.

False
True

The first print is inside the scope, so it prints False as the file is not closed, in the next print, the code is out of the scope, so the function prints True.

Append text to a file without using “with”

The “with” statement is useful because we don’t have to remember about closing the file. But if you don’t want to use it, you don’t have to. This is the way you can modify the code to get rid of the “with” statement.

import os

file_path = 'D://file.txt'
file_exists = os.path.isfile(file_path)

f = open(file_path, 'a')
f.write('First line.\n')
f.write('Second line.\n')

print(f.closed)
f.close()
print(f.closed)

There are two print functions at the end of the code to check whether the file object is opened before using the close() function, and closed after that.

When you run the code, you can see that it works well; it appends data to the file and closes the stream at the end.

Open for appending and reading (a+)

There is an additional file access mode you can use to append text to a file: a+.

This mode allows you to append to a file but also read it at the same time.

 Here’s how it works. First, delete the file and run this code:

file_path = 'D://file.txt'

with open(file_path, 'a+') as f:
    f.write('First line.\n')
    f.write('Second line.\n')
    f.write('Third line.\n')
    f.seek(2)
    data = f.read()

print(data)

By opening the file for appending and reading, we can use the seek() function to enter the position of the pointer as a parameter. This value represents the number of places that the pointer moves to the right. If you run the code, the two first characters are missing from the first line (indexing starts from 0).

rst line.
Second line.
Third line.

It’s important to mention, that the pointer is placed there only for reading. If you try to run the following code, the second line is not going to be placed before the first one.

file_path = 'D://file.txt'

with open(file_path, 'a+') as f:
    f.write('First line.\n')
    f.seek(0)
    f.write('Second line.\n')

The file is going to look like this.

If you change “a+” to “a”, and try to run the read() function, Python will return an error:

io.UnsupportedOperation: not readable

Append to a file, but overwrite the last line

The “append” file access mode ads new lines at the end of the file.

Let’s imagine a situation where you want to check if the last line of the file meets certain criteria. For example, if it contains a specific text and replaces it with a different one if the condition is met. Here’s an example. Add this text into file.txt.

This is 1st line.
This is 2nd line.
This is 3rd line.
---end of file---

We want to add two new lines: 4th and 5th. We don’t want the last line to be present inside the file, so we need to replace it.

with open("D://file.txt", "r+") as f:
    position = f.tell()
    line = f.readline()
    while '---end of file---' not in line:
        position = f.tell()
        line = f.readline()
    f.seek(position)
    f.write("This is 4th line.\n")
    f.write("This is 5th line.\n")

First, open the file for both reading and writing (r+). Next, check line by line for a particular string.

If the string is not met, the actual pointer is assigned to the position variable.

If the condition is met the position is remembered for the previous line. Next, let’s set the pointer to the previous line with the seek() function.

two additional lines are added starting from the pointer. This is the final result.

Append multiple lines at once

You can add multiple lines at the end of the file using the writeline function. This function takes a string or a list of strings as an argument.

Let’s use a file with the following lines.

This is 1st line.
This is 2nd line.
This is 3rd line.

Run this code.

lines_to_add = ['Additional line nr 1\n', 'Additional line nr 2\n']

with open("D://file.txt", "a+") as f:
    f.writelines(lines_to_add)

Two additional lines will be added at the end of the file.

This is 1st line
This is 2nd line
This is 3st line
Additional line nr 1
Additional line nr 2

Append as binary files

In Python, you can append files in binary mode. This is done using the ‘ab’ access.

with open('D://file.txt', 'ab') as f:
    line = 'Line in binary mode.'.encode()
    f.write(line)

print(line)
print(type(line))

The write() function in binary mode can’t take a standard string as a parameter. This string has to be encoded using the encode() function.

This code will add the line in binary mode.

At the end of the code, there are two print() functions.

The first function displays a line with the letter b at the beginning, indicating that this string uses a binary format.

The next function returns the type of this string: bytes.

b'Line in binary mode.'
<class 'bytes'>

If you open the file, it looks like this.