Append to File

Append text to an existing file without overwriting the previous content.

BeginnerTopic: File Handling Programs
Back

Python Append to File Program

This program helps you to learn the fundamental structure and syntax of Python programming.

Try This Code
# Program to append text to a file

filename = input("Enter filename to append to: ")
text = input("Enter text to append: ")

with open(filename, "a", encoding="utf-8") as f:
    f.write("\n" + text)

print("Text appended to", filename)
Output
Enter filename to append to: notes.txt
Enter text to append: Another line
Text appended to notes.txt

Understanding Append to File

Opening the file in "a" mode moves the file pointer to the end and preserves previous content.

Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.

Table of Contents