How To Append To A File Python

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.

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.

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.

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

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.