File Handling in Python
# File Handling in Python
Welcome to Chapter 16! File handling is essential for real-world programming — saving data, reading configurations, processing CSV files, and more.
---
1. Learning Objectives
- Open, read, write, and close files.
-
Use context managers (
withstatement).
- Work with different file modes.
- Read and write CSV files.
- Build a notes manager project.
---
2. Opening and Reading Files
```python id="py16_ex1" # Method 1: Open and close manually file = open("example.txt", "r") content = file.read() print(content) file.close()
# Method 2: Context manager (recommended!) with open("example.txt", "r") as file: content = file.read() print(content) # File is automatically closed after the block
python id="py16_ex2" with open("example.txt", "r") as f: # Read entire file content = f.read() # Read one line f.seek(0) # Reset position line = f.readline() # Read all lines as list f.seek(0) lines = f.readlines() # Iterate line by line (memory efficient) f.seek(0) for line in f: print(line.strip())
python id="py16_ex3" # Write mode ('w') — overwrites existing content with open("output.txt", "w") as f: f.write("Hello, World!\n") f.write("Python File Handling\n")
# Append mode ('a') — adds to end with open("output.txt", "a") as f: f.write("This line is appended!\n")
# Write multiple lines lines = ["Line 1\n", "Line 2\n", "Line 3\n"] with open("output.txt", "w") as f: f.writelines(lines)
python id="py16_ex4" import csv
# Writing CSV with open("students.csv", "w", newline="") as f: writer = csv.writer(f) writer.writerow(["Name", "Age", "Grade"]) writer.writerow(["Alice", 25, "A"]) writer.writerow(["Bob", 22, "B"]) writer.writerow(["Charlie", 23, "A"])
# Reading CSV with open("students.csv", "r") as f: reader = csv.reader(f) for row in reader: print(row)
# DictReader — read as dictionaries with open("students.csv", "r") as f: reader = csv.DictReader(f) for row in reader: print(f"{row['Name']}: Grade {row['Grade']}")
python id="py16ex5" import os
# Check if file exists print(os.path.exists("output.txt"))
# File info print(os.path.getsize("output.txt"))
# Rename and delete # os.rename("old.txt", "new.txt") # os.remove("file.txt")
# Directory operations # os.mkdir("newfolder") # os.listdir(".")
# pathlib (modern approach) from pathlib import Path
p = Path("output.txt") print(p.exists()) print(p.stem) # filename without extension print(p.suffix) # extension print(p.parent) # parent directory
python id="py16project" import os from datetime import datetime
NOTESFILE = "notes.txt"
def addnote(): note = input(" Enter note: ") timestamp = datetime.now().strftime("%Y-%m-%d %H:%M") with open(NOTESFILE, "a") as f: f.write(f"[{timestamp}] {note}\n") print(" ✅ Note saved!")
def viewnotes(): if not os.path.exists(NOTESFILE): print(" 📭 No notes yet!") return with open(NOTESFILE, "r") as f: notes = f.readlines() if not notes: print(" 📭 No notes yet!") else: print("\n 📝 Your Notes:") for i, note in enumerate(notes, 1): print(f" {i}. {note.strip()}")
def clearnotes(): confirm = input(" Clear all notes? (yes/no): ") if confirm.lower() == "yes": open(NOTESFILE, "w").close() print(" 🗑️ All notes cleared!")
print("=" * 40) print(" 📝 NOTES MANAGER") print("=" * 40)
while True:
print("\n 1. Add Note")
print(" 2. View Notes")
print(" 3. Clear Notes")
print(" 4. Exit")
choice = input("\n Choose (1-4): ")
if choice == "1": addnote()
elif choice == "2": viewnotes()
elif choice == "3": clearnotes()
elif choice == "4":
print(" 👋 Goodbye!")
break
``
---
8. Common Mistakes
-
1.
Not closing files: Always use with
(context manager).
-
2.
Using w
mode accidentally:Overwrites everything. Use ato append.
-
3.
FileNotFoundError: Check with os.path.exists()
before reading.
-
4.
Encoding issues: Use open("file.txt", "r", encoding="utf-8")
.
---
9. MCQs with Answers
Q1: Context manager keyword: A) open B) with C) file D) using Answer: B
Q2: 'w' mode does:
A) Reads only B) Appends C) Overwrites/creates D) Creates only
Answer: C
Q3: readlines() returns:
A) String B) List of strings C) Tuple D) Generator
Answer: B
Q4: To add to existing file: A) 'r' B) 'w' C) 'a' D) 'x' Answer: C
Q5: csv.DictReader returns rows as:
A) Lists B) Tuples C) Dicts D) Sets
Answer: C
Q6: with statement ensures:
A) Faster reading B) File is auto-closed C) File is encrypted D) Binary mode
Answer: B
Q7: Check if file exists: A) file.exists() B) os.path.exists() C) path.check() D) file.check() Answer: B
Q8: 'rb' mode is for:
A) Read text B) Read binary C) Read backward D) Read raw
Answer: B
Q9: pathlib.Path is:
A) Old-style B) Modern OOP file path handling C) Only for Linux D) Deprecated
Answer: B
Q10: newline="" in csv.writer prevents:
A) Errors B) Extra blank lines C) Unicode issues D) Slow writing
Answer: B
---
10. Interview Questions
-
1.
What is a context manager? An object implementing _enter
andexit_methods, used withwithto manage resources.
-
2.
Difference between read(), readline(), readlines()? read()
returns entire content,readline()one line,readlines()list of all lines.
-
3.
How to read large files efficiently? Iterate line by line with for line in file:
instead ofread()orreadlines().
- 4. os.path vs pathlib? pathlib (Python 3.4+) is the modern, OOP approach; os.path is older but still common.
-
5.
How to handle file encoding? Specify encoding="utf-8"
inopen().
---
11. Summary
-
Use with open()
(context manager) for automatic file closing.
-
Modes: r
(read),w(write/overwrite),a(append),x(create).
-
Use csv
module for CSV files.
-
Use os.path
orpathlibfor file system operations.
- Always handle FileNotFoundError` gracefully.
---
12. Next Chapter Recommendation
In Chapter 17: Exception Handling, you'll learn to handle errors gracefully with try/except/finally! 🚀