Skip to content
Zeni Study
  • Pages
    • Learn Python In 7 Days
      • Day 1 : Variable + if/else
      • Day 2: Loops
      • Day 3 : Array + String
      • Day 4 — Functions
      • Day 5 — Dictionaries - Hashmap
      • icon picker
        Day 6 — Files & Errors
      • Day 7 — Mini Project & Programmer Thinking
    • Machine Coding:
      • Day 1 — Bank account + Wallet :
      • Day 2 : RateLimiter + seat booking
      • Day 3 : Library Management + Classroom Attendance System
      • Day 4 : Bank account and notification system.
      • Day 5 : Key-value and payment processor.
      • Day 6 : Discount engine + Seat booking( in depth)
      • Day 7: Parking lot System :
    • Machine coding extended:
      • Day 7.5 — Parking Lot (Constraint-Heavy Variant)
      • Day 8 : Order + Payment System
      • Day 8 — Extension Round (Mid-Interview Change)
      • Day 9 — Ticket Booking with Expiry (Simulated Time)
      • Day 9 — Extension Round (Seat Lock Ownership + Forced Unlock)
    • SQL + DB Thinking course
      • Day 1 — Tables, Rows & Thinking in Data
      • Day 2 — Relationships & Foreign Keys (Thinking in Connections)
      • Day 3 — Filtering, Aggregation & Answering Data Questions
      • Day 4 — JOINs (Combining Tables the Right Way)
      • Day 5 — Subqueries, EXISTS & NOT EXISTS (Thinking in Layers)
      • Day 6 — Indexes, Constraints & How Databases Think
      • Day 7 — Full SQL Interview Simulation (SDE-1 Ready)
      • Extended Day 1 — Core Business Systems (Deep Practice)
      • Extended Day 2 — Booking & Platform Systems (High-Depth Practice)
      • Extended Day 3 — Content & Learning Platforms (Capstone Practice)
    • LLD: Java
      • DAY 1 — Core Foundations (SDE-2 Level)
      • DAY 2 — State, Time & Domain Correctness
      • DAY 3 — Extensibility & Failure Handling (SDE-2 Core Signal)
      • DAY 4 — Concurrency, Scheduling & Consistency (SDE-2 Critical)
      • DAY 5 — Workflow Design & Config-Driven Systems (SDE-2+)
      • DAY 6 — Eventing & Usage-Based Systems (Advanced SDE-2)
      • DAY 7 — Interview Simulation (Hard, Production-Grade)
      • Hidden Edge Cases Interviewers Expect (Day-wise)
      • Detailed Testing file:
    • Assignment:
      • If else Practice Set

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

Forgetting to close file
Using "w" instead of "a"
Not handling invalid input
Assuming file always exists
Putting too much code inside try

🧪 Practice Questions (Very Important)

Think → write steps → then code.

Q1

Write a program to take user input and save it to a file.

Q2

Read a file and print number of lines in it.

Q3

Read a file and count number of words.

Q4

Ask user for filename and display its content. Handle case when file does not exist.

Q5

Take numbers from user until user types "stop". Save all numbers to a file.

Q6

Read numbers from file and print their sum.

Q7 (Thinking Question)

Why should we not trust user input or file content?
Answer in words.

🔑 HINTS (Read Together, Only If Stuck)

Use .split() to count words
Use counter variable for lines
Convert string to int carefully
Use try / except only where needed
Always close files or use with
Assume input can be wrong

✅ What You Should Be Able to Do Now

After Day 6, you should:
Save data permanently
Read data from files
Handle errors safely
Write programs that don’t crash
Think about failure cases

🧠 Reflection Questions (Answer in Words)

Why do programs need files?
Difference between write and append?
Why is with better?
Why should errors be handled?

⭐ Golden Rule from Day 6

A real program is not the one that works once, but the one that works even when things go wrong.
If you say “Continue with Day 7”, next we’ll do:
A full mini-project
Combining all concepts
How to think like a programmer
Confidence-building final day
One last step to complete the journey.
 
Want to print your doc?
This is not the way.
Try clicking the ··· in the right corner or using a keyboard shortcut (
CtrlP
) instead.