Python Program to Append Text to a File
Beginner · File handling
Appending adds new text to the end of a file and keeps what was already there. Opening a file in "a" (append) mode does this, while "w" mode would erase the file first. This program makes a small diary file, appends two new entries, and shows the file before and after.
Program
Before appending: Monday: Learned about lists Tuesday: Practised loops After appending: Monday: Learned about lists Tuesday: Practised loops Wednesday: Wrote my first file program Thursday: Learned the file modes
How it works
- The program first writes two lines in "w" mode, so there is a file to append to; "w" also empties it, so every run starts from the same two lines.
- Opening the same file with
"a"puts the writing position at the end of the file, so the old lines are kept. - Each new entry ends with
"\n", so the next entry starts on a line of its own. - If the file does not exist yet,
"a"creates it, just like"w"does.
Other ways to write it
The difference between "w" and "a"
Mode "w": ['new line'] Mode "a": ['old line', 'new line']
Both runs start from the same one-line file. Mode "w" wipes the old line before writing, while mode "a" keeps it and adds the new line after it.
Appending with a function
Shopping list: ['milk', 'bread', 'eggs', 'rice']
Each call opens the file in append mode, adds one line and closes it again, which is how log files grow one entry at a time.
Try it yourself
Append the lines "Item 1" to "Item 5" in a loop, then print the file to check all five were added.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
- Write to a File
- Read a File Line by Line
- Count the Lines in a File
- Store and Search User IDs and Passwords in a CSV File
- Read a Text File and Separate Words with #
- Count Vowels, Consonants, Uppercase and Lowercase Characters in a Text File
- Copy Lines Without the Letter 'a' to Another File
- Search a Roll Number in a Binary File
- Update Marks in a Binary File
- Count the Words "Me" and "My" in a Text File
All Python programs · CBSE class 12 practical file · Python exercises