Perfect 🔥 Rajeev —
Let’s now do the Practice Worksheet for File & Exception Handling (with step-by-step solutions + explanations)

This section turns the tutorial into an interactive learning lab — like you’d see in professional coding bootcamps.


🧮 FILE & EXCEPTION HANDLING — PRACTICE WORKSHEET

We’ll go from Basic → Intermediate → Advanced → Industry-Level Challenges.


🟢 LEVEL 1: BASIC PRACTICE

🧩 Q1. Create a text file and write “Python is amazing” inside it.

Goal: Practice basic writing.

Solution:

with open("practice1.txt", "w") as f:
    f.write("Python is amazing")

🧩 Q2. Read and print the content from the above file.

Solution:

with open("practice1.txt", "r") as f:
    data = f.read()
    print(data)

🧩 Q3. Append a new line: “File handling is powerful.”

Solution:

with open("practice1.txt", "a") as f:
    f.write("\nFile handling is powerful.")

🧩 Q4. Count how many lines are in the file.

Solution:

with open("practice1.txt", "r") as f:
    lines = f.readlines()
    print("Total lines:", len(lines))

🟡 LEVEL 2: INTERMEDIATE PRACTICE

🧩 Q5. Read a file line by line and print line numbers alongside.

Solution:

with open("practice1.txt", "r") as f:
    for i, line in enumerate(f, start=1):
        print(f"Line {i}: {line.strip()}")

🧩 Q6. Write 5 user input lines into a file.

Solution:

with open("user_input.txt", "w") as f:
    for i in range(5):
        data = input(f"Enter line {i+1}: ")
        f.write(data + "\n")

🧩 Q7. Safely open a file — if it doesn’t exist, create it.

Solution:

try:
    with open("safe_file.txt", "r") as f:
        print(f.read())
except FileNotFoundError:
    with open("safe_file.txt", "w") as f:
        f.write("Auto-created file.")
    print("File was missing. Created a new one.")

🧩 Q8. Read and count how many times a word (e.g. “Python”) appears in a text file.

Solution:

word = "Python"
count = 0
with open("practice1.txt", "r") as f:
    for line in f:
        count += line.count(word)
print(f"'{word}' appears {count} times.")

🟠 LEVEL 3: ADVANCED CONCEPTS

🧩 Q9. Handle multiple possible exceptions during file reading.

Goal: Catch multiple exceptions properly.

Solution:

try:
    with open("practice1.txt", "r") as f:
        print(f.read())
except FileNotFoundError:
    print("File missing!")
except PermissionError:
    print("Access denied!")
except Exception as e:
    print(f"Unexpected error: {e}")

🧩 Q10. Create a custom exception for invalid filename.

Solution:

class InvalidFilenameError(Exception):
    pass

def read_file(filename):
    if not filename.endswith(".txt"):
        raise InvalidFilenameError("Only .txt files are allowed.")
    with open(filename, "r") as f:
        print(f.read())

try:
    read_file("sample.csv")
except InvalidFilenameError as e:
    print("Custom Error:", e)

🧩 Q11. Use a custom context manager to auto-handle files.

Goal: Understand how with works under the hood.

Solution:

class MyFile:
    def __init__(self, filename, mode):
        self.filename = filename
        self.mode = mode
    def __enter__(self):
        self.file = open(self.filename, self.mode)
        return self.file
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.file.close()
        print("File closed automatically!")

with MyFile("test.txt", "w") as f:
    f.write("Learning custom context managers.")

🧩 Q12. Write a log file that records all exceptions occurring in a program.

Solution:

import logging

logging.basicConfig(filename="error.log", level=logging.ERROR)

try:
    num = int(input("Enter a number: "))
    print(10 / num)
except Exception as e:
    logging.error("An error occurred", exc_info=True)
    print("Error logged in file.")

🧠 Used widely in production — logs every issue for post-mortem debugging.


🔵 LEVEL 4: REAL-WORLD MINI PROJECTS


🧩 Q13. Build a Safe File Reader Utility

This function should:

  • Check if the file exists
  • Handle permission errors
  • Log any unexpected issues

Solution:

import os
import logging

logging.basicConfig(filename='file_errors.log', level=logging.ERROR)

def safe_read(filepath):
    try:
        with open(filepath, 'r') as f:
            return f.read()
    except FileNotFoundError:
        print(f"{filepath} not found. Creating empty file.")
        with open(filepath, 'w') as f:
            f.write("")  # create empty file
        return ""
    except PermissionError:
        print("Permission denied.")
        return None
    except Exception as e:
        logging.error(f"Unexpected error for {filepath}", exc_info=True)
        return None
    finally:
        print("Operation completed.")

# Test
print(safe_read("data.txt"))

🧩 Q14. Create a file merger that combines all .txt files in a folder.

Solution:

import os

folder = "."
merged_content = ""

for file in os.listdir(folder):
    if file.endswith(".txt"):
        with open(file, "r") as f:
            merged_content += f"\n--- {file} ---\n" + f.read()

with open("merged_output.txt", "w") as out:
    out.write(merged_content)

print("All text files merged into merged_output.txt")

Used in ETL jobs, log aggregation, and batch processing.


🧩 Q15. Build an exception-safe file copier.

Solution:

def copy_file(source, destination):
    try:
        with open(source, "r") as src, open(destination, "w") as dest:
            dest.write(src.read())
        print("File copied successfully.")
    except FileNotFoundError:
        print("Source file not found.")
    except PermissionError:
        print("Permission denied.")
    except Exception as e:
        print("Unexpected error:", e)

copy_file("practice1.txt", "backup.txt")

🔴 LEVEL 5: BONUS CHALLENGE (PRO CODER MODE)

🧩 Q16. Implement retry logic if a file is temporarily unavailable.

Solution:

import time

def read_with_retry(file, retries=3):
    for attempt in range(retries):
        try:
            with open(file, "r") as f:
                return f.read()
        except FileNotFoundError:
            print(f"Attempt {attempt+1}: File not found, retrying...")
            time.sleep(2)
    print("All retries failed.")
    return None

read_with_retry("tempfile.txt")

Industry use: Retry systems in ETL and distributed jobs when file systems lag.


🧠 MINI INTERVIEW PRACTICE RECAP

ConceptPractice Question
File open/closeWhat does with open() do internally?
Exception blockWhat happens if you have try with no except but with finally?
Custom exceptionsWhy use them and where?
Context managersWhat methods must a context manager define?
LoggingWhy is logging preferred over print()?
File operationsDifference between 'a' and 'w' mode?
Retry patternWhy retry logic is crucial in data engineering jobs?

Pages: 1 2

Posted in

Leave a Reply

Your email address will not be published. Required fields are marked *