🚀 Day 86/150 – File Append Operation in Python
Appending data to a file is a common task in Python when you want to add new content without deleting the existing data. This is useful for maintaining logs, storing records, or continuously updating files. In this post, we'll explore different ways to append data to a file.
Method 1 – Using append Mode ("a")
Open a file in append mode and write new data to the end of the file.
file = open("sample.txt", "a") file.write("Hello, Python!\n") file.close()
Output (sample.txt)
Existing Content
Hello, Python!
Explanation:
- "a" opens the file in append mode.
- New content is added to the end of the file.
- Existing content remains unchanged.
Method 2 – Using the with Statement
Using with is the safest and recommended way to append data.
with open("sample.txt", "a") as file: file.write("Welcome to File Handling!\n")
Output (sample.txt)
Existing ContentWelcome to File Handling!
Explanation:
- The file is automatically closed after the operation.
- Cleaner and safer than manually calling close().
Method 3 – Appending Multiple Lines
Use writelines() to append multiple lines at once.
lines = [ "Python\n", "Java\n", "C++\n" ] with open("sample.txt", "a") as file: file.writelines(lines)
Output (sample.txt)
Existing Content
Python
Java
C++
Explanation:
- writelines() appends each string in the list.
- Include \n to place each item on a new line.
Method 4 – Taking User Input
Append text entered by the user to a file.
Learning Python every day!text = input("Enter text to append: ") with open("sample.txt", "a") as file: file.write(text + "\n") print("Data appended successfully!")
Sample Input
Output (sample.txt)
Existing ContentLearning Python every day!
Explanation:
- Accepts input from the user.
- Adds the new text to the end of the file.
- Preserves all existing data.
Comparison of Methods
| Method | Best For |
|---|---|
| write() with "a" | Appending a single line |
| with open() | Safe and recommended file handling |
| writelines() | Appending multiple lines |
| User Input | Saving user-generated data |
🔥 Key Takeaways
- Use "a" mode to append data without deleting existing content.
- The with statement is the recommended way to work with files.
- Use writelines() to append multiple lines efficiently.
- Append mode automatically creates the file if it doesn't already exist.
- File appending is commonly used for logs, reports, and maintaining records.
Stay tuned for Day 87 of the #150DaysOfPython series! 🚀

