File Handling in Python
💡 Why File Handling Matters:
We’ve built apps that:
Use input/output
Store info temporarily
Now we’ll learn how to:
Store data permanently
Read & write text files
Build systems that remember informations like:
Saving receipts
Storing student reports
Logging login attempts
1. Open a File
This creates a file and writes inside it. "w" = write mode (creates/overwrites)
2. Read from a File
This reads what you wrote earlier.
57
3. Add (Append) to a File
"a" = append mode (adds without deleting old data)
🧼 4. Best Practice: Use with (Auto Close)
✅ This way Python closes it for you automatically — cleaner and safer.
Example:
Build a simple student note keeper:
1.Ask the user to type their name and a note
2.Save it in a file called notes.txt
3.Each time the app runs, it should add a new line like:
58
Sample Output:
After User runs the app:
🗂️ File: notes.txt will now contain:
If another user runs the code:
✅ File content becomes:
🧠 What You Just Learned:
Writing to files using "a" mode (append)
Formatting strings with f"{...}"
Using with open(...) as file: for clean file handling
59
Mini-Lesson Search or Filter Notes in a File
🎯 Goal:
Ask the user to enter a name
Read the notes.txt file
Show only the notes written by that name
Example: Enter name to search: Brighton
📌 Found note: Brighton: I love Python!
If no match:
Enter name to search: Asha
❌ No notes found for: Asha
FULL CODE: Search Notes by Name
🧠 What You Just Learned:
Text searching
60
Looping through file lines
String functions like .startswith()
Graceful error handling