Skip to content

Day 6 — Files & Errors

🟢 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
Expense data resets
Scores are lost
💡 Programs need memory that survives after closing. That memory is called a file.

2️⃣ Real-World Analogy

Think of:
Notebook → file
Writing → saving data
Reading → loading data
🧠 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

Open file in write mode
Write text
Close file (VERY IMPORTANT)
🧠 If you don’t close the file, data may not be saved.

4️⃣ File Modes (Only What You Need)

Mode
Meaning
"w"
Write (overwrites file)
"a"
Append (adds to file)
"r"
Read
There are no rows in this table

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
Safer
Cleaner code
🧠 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

Try code inside try
If error occurs → jump to except
Program continues safely

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:
Talks to user
Reads file
Converts data
Ask:
“What can go wrong here?”
Then handle it.

⚠️ Common Beginner Mistakes

 
Want to print your doc?
This is not the way.
Try clicking the ··· in the right corner or using a keyboard shortcut (
CtrlP
) instead.