How do you append to a file with Python?


The task of appending content to a file is a common and routine task in Python programming. If you need to log data, store user inputs, or update a configuration file, appending makes it possible for you to add new data or information to a file without overwriting existing content. Here, in this article, we will explore various ways of how to append to a file using Python; we also demonstrate through some code examples with explanations to guide you through the process.

You will get to know how to append content to a file using Python in many different scenarios. You can follow the given examples to understand how to open a file in append mode and add new data to it. You will get hands-on practical experience with code snippets that are described in a user-friendly manner.

Appending a Single Line of Text to a File

In order to append a single line of text to a file, you follow these steps:

  • Step 1: You open the file in append mode using the open() function. You can provide the file path as the first argument and use the mode 'a' to open the file in append mode.

  • Step 2: You use the write() method to add content to the file. You pass the text you want to append as the argument to the write() method.

  • Step 3: Finally, you close the file using the close() method to free up system resources.

Example

The example code snippet given below demonstrates the process:

Suppose we have a text file as shown below

#myfile.txt
This is a test file

We open the file in append mode and then append a line of text before closing the file.

# Open the file in append mode
file = open('myfile.txt', 'a')
#Append content to the file
file.write('\n This is a new line of text.')

# Close the file
file.close()

When we run the above code we get the following output when the myfile.txt is opened.

Output

#myfile.txt
This is a test file
This is a new line of text

Appending Multiple Lines of Text to a File

The process of appending multiple lines of text to a file is same as appending a single line of text to the file. However, you can make use of a ‘for loop’ to add each line individually or separately. Let us consider an example that illustrates the process:

Example

Suppose we have a text file as follows.

#myfile.txt
This is a test file

# Open the file in append mode
file = open('myfile.txt', 'a')
# Create a list of lines to append
lines = ['\n Line 1\n', 'Line 2\n', 'Line 3\n']

# Append each line to the file
for line in lines:
   file.write(line)

# Close the file
file.close()

When we run the above code we get the following output when the myfile.txt is opened.

Output

#myfile.txt
This is a test file
Line 1
Line 2
Line 3

Appending User Inputs to a File

One more thing can be done; you can also append user inputs to a file. We have here an example that tells or prompts the user for input and appends the same to the desired file:

Example

Suppose we have a text file as follows.

#myfile.txt
This is a test file

# Open the file in append mode
file = open('myfile.txt', 'a')

# Prompt the user for input
user_input = input("Enter some text: ")

# Append the user input to the file
file.write(user_input)

# Close the file
file.close()

When we run the above code and enter “This is test input text” at the input prompt, we get the following output when the myfile.txt is opened.

Output

#myfile.txt
This is a test file 
This is test input text

Appending a List of Data to a File

There are multiple ways appending to a file can be done. One such situation is when appending a list of data to a file that can be useful when you want to store structured information. You need to follow these steps to append a list of data to a file:

  • Step 1: You open the file in append mode using the open() function. You specify the file path as the first argument and use the mode 'a' to open the file in append mode.

  • Step 2: You create a list containing the data you want to append.

  • Step 3: You then use a loop to iterate through the list and append each element to the file using the write() method.

  • Step 4: At last, you can close the file using the close() method to make sure proper resource management.

Example

#data.txt
# Open the file in append mode
file = open('data.txt', 'a')

# Create a list of data to append
data_list = ['Jane', 'Doe', '21', 'jane.doe@example.com']

# Append each element to the file
for item in data_list:
   file.write(item + '\n')

# Close the file
file.close()

When we run the above code, we get the following output when the data.txt file is opened.

Output

Jane
Doe
21
jane.doe@example.com

Appending JSON Data to a File

In this case, we are going to append JSON (JavaScript Object Notation) data to a file which is useful when you want to store structured data in a readable format. You can follow these given steps to append JSON data to a file:

  • Step 1: You open the file in append mode using the open() function. You specify the file path as the first argument and use the mode 'a' to open the file in append mode.

  • Step 2: You import the JSON module.

  • Step 3: You create a Python dictionary or list containing the data you want to append.

  • Step 4: You can use the json.dump() function to write the JSON data to the file.

  • Step 5: Lastly, you can close the file using the close() method.

Example

Let us here consider an example code snippet that shows how to append JSON data to a file:

Suppose we create an empty data.json file

#data.json
import json

# Open the file in append mode
file = open('data.json', 'a')

# Create a dictionary or list to append
data = {'name': 'Jane Doe', 'age': 21, 'email': 'jane.doe@example.com'}

# Append the JSON data to the file
json.dump(data, file)

# Add a newline character to separate entries (optional)
file.write('\n')

# Close the file
file.close()

When we run the above code, we get the following output when the data.json file is opened.

Output

{"name": "Jane Doe", "age": 21, "email": "jane.doe@example.com"}

The operation of appending text or data to a file in Python is a simple and straightforward task. When you open a file in append mode and use the write() method, you can easily add or append new content to an existing file without overwriting its contents. Here, in this article, we navigated through some examples that showcased how to append a single line, multiple lines, and user inputs to a file. We also made provisions for additional examples to demonstrate appending a list of data and appending JSON data to a file. By following easily comprehensible explanations and code snippets, you can gain a better knowledge of how to append various types of data to files using Python. You need to keep in mind that is mandatory to close the file after appending to ensure proper handling of system resources.

Updated on: 13-Jul-2023

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements