Append content to a file in Python
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:
|
1 2 3 |
with open('file.txt', 'a') as f: f.write('Thank you.\n') |
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.
|
1 2 3 |
with open('file.txt', 'a+') as f: f.write('Thank you.\n') |
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.
|
1 2 3 4 5 6 |
import os with open('file.txt', 'r+') as f: f.seek(0, os.SEEK_END) f.write('Thank you.\n') |
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').
|
1 2 3 4 5 |
import io with io.open("file.txt", mode='a', encoding='utf-8') as f: f.write('Thank you.\n') |
That’s all about appending content to a file in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)