🟢 Day 6 — Files & Errors (Making Programs Real and Reliable)
1️⃣ Why Do We Need Files?
Until now, every program had this problem:
When the program ends, everything is forgotten.
Real-world problem
Student records disappear 💡 Programs need memory that survives after closing.
That memory is called a file.
2️⃣ Real-World Analogy
Think of:
🧠 File = long-term memory
Variables = short-term memory
3️⃣ Writing Data to a File
Basic Example
file = open("data.txt", "w")
file.write("Hello World")
file.close()
How Computer Thinks
Close file (VERY IMPORTANT) 🧠 If you don’t close the file, data may not be saved.
4️⃣ File Modes (Only What You Need)
Append Example
file = open("data.txt", "a")
file.write("\nNew Line")
file.close()
💡 Append is safer than write if you don’t want to lose data.
5️⃣ Reading Data from a File
file = open("data.txt", "r")
content = file.read()
file.close()
print(content)
Reading Line by Line
file = open("data.txt", "r")
for line in file:
print(line)
file.close()
🧠 Line-by-line reading is used for large files.
6️⃣ The with Statement (Best Practice)
with open("data.txt", "r") as file:
content = file.read()
Why better?
Automatically closes file 🧠 Always prefer with when possible.
7️⃣ Errors Are Normal (Crashes Are Not)
Example Crash
x = int(input("Enter number: "))
If user enters "abc" → ❌ program crashes.
💡 Errors WILL happen in real life.
8️⃣ Handling Errors Using try / except
try:
x = int(input("Enter number: "))
print(x)
except:
print("Invalid input")
How Computer Thinks
If error occurs → jump to except 9️⃣ Handling File Errors
File Not Found Example
try:
with open("missing.txt", "r") as file:
print(file.read())
except:
print("File does not exist")
🧠 Programs should fail gracefully, not crash.
🔁 Key Thinking Pattern of Day 6
Whenever your program:
Ask:
“What can go wrong here?”
Then handle it.
⚠️ Common Beginner Mistakes