Append to File

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

PythonBeginner
Python
# 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

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