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 browser1# Program to append text to a file23filename = input("Enter filename to append to: ")4text = input("Enter text to append: ")56with open(filename, "a", encoding="utf-8") as f:7 f.write("\n" + text)89print("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.