In this tutorial, we will learn how to append to a file in Python. Appending data to a file is a common operation when working with files, as it adds new data to an existing file without erasing or modifying the existing data. We will explore different methods of appending data to a file in Python and their limitations with examples.
Step 1: Creating a sample text file
First, let’s create a sample text file to work with. In this example, we will be working with a text file named “example.txt” which contains the following content:
Hello, World!
Step 2: Writing the code to append data
To append data to a file, we can use the open
function with the file mode set to ‘a’ (append). In this mode, the file pointer is placed at the end of the file, and any data written to the file will be added at the end.
1 2 |
with open('example.txt', 'a') as file: file.write('\nThis is a new line.') |
The code above opens “example.txt” in append mode and writes “This is a new line.” to it.
Output:
Hello, World! This is a new line.
Method 2: Using the os
module
Step 1: Importing the os module
We can also append data to a file using the os
module. First, we need to import the os
module.
1 |
import os |
Step 2: Writing the code to append data
Now that we have imported the os
module, we can use its functions to open a file in append mode and write data to it.
1 2 |
with os.fdopen(os.open('example.txt', os.O_APPEND | os.O_CREAT | os.O_WRONLY), 'a') as file: file.write('\nThis is another new line.') |
The code above combines os.open
and os.fdopen
to open the file in append mode and write the specified data to it.
Output:
Hello, World! This is a new line. This is another new line.
Full Code Example
1 2 3 4 5 6 7 8 9 |
import os # Using basic file I/O functions with open('example.txt', 'a') as file: file.write('\nThis is a new line.') # Using the os module with os.fdopen(os.open('example.txt', os.O_APPEND | os.O_CREAT | os.O_WRONLY), 'a') as file: file.write('\nThis is another new line.') |
Sample content of example.txt after running the code:
Hello, World! This is a new line. This is another new line.
Conclusion
In this tutorial, we learned how to append to a file in Python using basic file I/O functions and the os
module. Appending data to a file allows us to add new data without deleting or altering the existing data in the file. Practice these methods to become familiar with working with files in Python.