Append Data to an Existing File in Python

To append data to an existing file in Python, you can open the file in append mode ('a') or append and read mode ('a+') using the open() function. This ensures that new content is added to the end of the file without deleting existing data.


Examples for Appending Data to an Existing File

1. Appending Text to an Existing File

We will append a new line of text to an existing file named example.txt. If the file does not exist, Python will create it automatically.

main.py

</>
Copy
# Opening the file in append mode
with open("example.txt", "a") as file:
    file.write("\nThis is a new line of text.")

print("Text appended successfully!")

Explanation:

  1. The file is opened in 'a' (append mode), meaning new content is added at the end without removing existing data.
  2. file.write("\nThis is a new line of text.") adds a newline character \n to ensure the new text starts on a new line.
  3. The with open statement ensures that the file closes automatically after writing.

Output:

After executing the code, the file example.txt will contain the newly appended text.

2. Appending Multiple Lines Using a List

We can append multiple lines to a file by writing a list of strings using the writelines() method.

main.py

</>
Copy
# Opening the file in append mode
with open("example.txt", "a") as file:
    lines = ["\nPython is powerful.", "\nAppending data is easy.", "\nFile handling is useful."]
    file.writelines(lines)

print("Multiple lines appended successfully!")

Explanation:

  1. The file is opened in append mode using 'a'.
  2. A list lines is created, containing multiple strings.
  3. The writelines() function writes all strings in the list to the file without adding newlines automatically.

Output:

The text will be added to example.txt as specified in the list.

3. Appending User Input to a File

In this example, the user is asked to enter text, which will be appended to the file.

main.py

</>
Copy
# Asking for user input
user_input = input("Enter text to append: ")

# Opening the file in append mode
with open("example.txt", "a") as file:
    file.write("\n" + user_input)

print("User input appended successfully!")

Explanation:

  1. The program takes user input using input().
  2. The file is opened in append mode.
  3. The user input is written to the file, preceded by a newline character \n to maintain proper formatting.

Output (Example Run):

The entered text will be appended to example.txt.

4. Appending a Timestamp to a File

We can log timestamps into a file each time a script runs using the datetime module.

main.py

</>
Copy
from datetime import datetime

# Getting current timestamp
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

# Opening the file in append mode
with open("log.txt", "a") as file:
    file.write("\nLog Entry: " + timestamp)

print("Timestamp appended successfully!")

Explanation:

  1. The datetime.now().strftime() function generates a timestamp in “YYYY-MM-DD HH:MM:SS” format.
  2. The file log.txt is opened in append mode.
  3. The timestamp is written to the file as a log entry.

Output:

Every execution of this script will add a new timestamp to log.txt.

Conclusion

Appending data to an existing file in Python is simple using the open() function with append mode. Here are the key takeaways from this tutorial:

  1. Use 'a' mode to append text to a file.
  2. Use writelines() to append multiple lines at once.
  3. Accept user input and write it to a file dynamically.
  4. Log timestamps by appending them with each execution.