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
Run in browser
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.