This post will discuss how to append text at the end of a file in Python.

1. Using open() function

The standard approach is to open the file in append mode ('a') with the built-in open() function and then use the write() function to write text to it. The text is added at the end of a file since the stream is always positioned at the end of the file in 'a' mode. Here’s what the code would look like:

 
If the file does not exist, it is created with 'a' mode. Additionally, if you need to read text from the file, use the 'a+' mode. It allows you to seek backward and read, but subsequent writes to the file will still end up at the end of the file.

 
Alternatively, you can open the file in 'r+' mode, allowing both reading and writing. However, the stream is positioned at the beginning of the file. Therefore, you need to set the stream at the end of the file to append text to the file.

2. Using io module

Another option is to use the io.open() function, which is an alias for the built-in open() function. To append text to a file, use the append mode ('a').

That’s all about appending content to a file in Python.