Append to File in Python

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

BeginnerFile Handling ProgramsExample 3 of 20
append-to-file.py
1# Program to append text to a file
2
3filename = input("Enter filename to append to: ")
4text = input("Enter text to append: ")
5
6with open(filename, "a", encoding="utf-8") as f:
7 f.write("\n" + text)
8
9print("Text appended to", filename)

Output

Enter filename to append to: notes.txt
Enter text to append: Another line
Text appended to notes.txt

What's going on

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

After this program

If the idea is still fuzzy, read Day 14: File Handling in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 20 file handling programs, or see every topic on Python exercises.