MODULE 07

File Handling

Read & Write Files, Text Processing, CSV, JSON, File Pointers, Exception Handling & Practical File Projects — explained step by step.

8Major Topics
45Detailed Subtopics
30Coding Questions
30Theory Q&A
TOPIC 01

1. File Handling Introduction

1.1 What is file handling?

File handling is the process of creating, opening, reading, writing, updating, and closing files from Python programs. It allows data to persist after a program finishes.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.

1.2 Why file handling is important

Files are useful for storing reports, logs, configuration, user data, text, CSV records, JSON data, and application output.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.

1.3 File workflow

The basic workflow is: identify the file path, open the file in the required mode, perform the operation, and close it. Using with is recommended because it closes the file automatically.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.

1.4 Text vs binary files

Text files store characters and are commonly used for .txt, .csv, and .json files. Binary files store raw bytes and are used for formats such as images, PDFs, audio, and executable files.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.
TOPIC 02

2. Opening Files

2.1 open()

The open() function connects Python to a file. A basic example is open('data.txt', 'r'). It returns a file object.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.

2.2 File modes

Common modes are r for reading, w for writing, a for appending, x for exclusive creation, b for binary, and + for updating/read-write access.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.

2.3 Read mode

Mode r opens an existing file for reading. If the file does not exist, Python raises FileNotFoundError.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.

2.4 Write mode

Mode w creates a new file or truncates an existing file before writing. Be careful because existing contents can be replaced.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.

2.5 Append mode

Mode a adds new content to the end of an existing file and creates the file if it does not already exist.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.

2.6 with statement

with open(...) as file automatically manages the file resource and closes it after the indented block finishes, including when an exception occurs.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.
TOPIC 03

3. Reading Files

3.1 read()

read() returns file content as one string. You can optionally provide a size to limit how many characters or bytes are read.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.

3.2 readline()

readline() reads one line at a time. Repeated calls continue from the current file position.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.

3.3 readlines()

readlines() returns the remaining lines as a list. It is convenient for small files but can use more memory for very large files.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.

3.4 Looping through a file

A file object is iterable, so for line in file: is an efficient way to process a text file line by line.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.

3.5 File pointer

The current position can be inspected with tell() and changed with seek().

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.

3.6 strip()

line.strip() removes surrounding whitespace, including the newline character, making lines easier to process.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.
TOPIC 04

4. Writing and Updating Files

4.1 write()

write() writes a string to a file and returns the number of characters written.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.

4.2 writelines()

writelines() writes an iterable of strings. It does not automatically add newline characters, so include them when required.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.

4.3 Append records

Append mode is useful for adding log entries or new records without deleting previous data.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.

4.4 Read and write together

Modes such as r+ and w+ allow combinations of reading and writing. Choose the mode carefully because w+ truncates the file.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.

4.5 Encoding

Text files can be opened with an explicit encoding such as encoding='utf-8' to handle Unicode text reliably.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.
TOPIC 05

5. CSV File Handling

5.1 What is CSV?

CSV stands for Comma-Separated Values. It is a simple tabular format commonly used for spreadsheets, databases, reports, and data exchange.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.

5.2 csv.reader()

csv.reader() reads rows as sequences of values. It is useful when you want to process CSV data row by row.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.

5.3 csv.writer()

csv.writer() writes rows to a CSV file and handles quoting and delimiters.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.

5.4 DictReader

csv.DictReader reads each row as a dictionary using column headers as keys.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.

5.5 DictWriter

csv.DictWriter writes dictionary records using a defined list of fieldnames.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.

5.6 CSV best practices

Use newline='' when opening CSV files with Python's csv module, specify encoding when needed, and validate important fields before processing.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.
TOPIC 06

6. JSON File Handling

6.1 What is JSON?

JSON is a text-based data-interchange format commonly used by APIs and applications. It represents objects, arrays, strings, numbers, booleans, and null.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.

6.2 json.dumps()

dumps() converts a Python object into a JSON-formatted string.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.

6.3 json.loads()

loads() converts a JSON string into a Python object.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.

6.4 json.dump()

dump() writes a Python object directly to a JSON file.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.

6.5 json.load()

load() reads JSON from a file and converts it into a Python object.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.

6.6 JSON formatting

indent can make JSON easier for humans to read. sort_keys can provide stable key ordering for readable output.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.
TOPIC 07

7. Exception Handling

7.1 What is an exception?

An exception is a runtime event that interrupts normal program execution, such as division by zero, invalid conversion, missing files, or invalid indexes.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.

7.2 try and except

Put risky code inside try and handle expected errors inside except blocks.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.

7.3 Multiple exceptions

You can handle different exception types using multiple except blocks or a tuple of exception classes.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.

7.4 else

The else block runs only when the try block completes without raising an exception.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.

7.5 finally

The finally block runs whether an exception occurs or not. It is useful for cleanup.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.

7.6 raise

raise allows your program to deliberately generate an exception when a business rule or validation fails.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.

7.7 Custom exceptions

A custom exception can be created by defining a class that inherits from Exception. This makes application-specific errors clearer.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.
TOPIC 08

8. Practical File Projects

8.1 Text log system

A simple log system can append timestamped messages to a text file and later read them line by line.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.

8.2 CSV student records

Student data can be stored in CSV rows with fields such as ID, name, course, and marks, then read and calculated by Python.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.

8.3 JSON configuration

JSON is useful for configuration and structured application data because it maps naturally to Python dictionaries and lists.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.

8.4 Safe file processing

Validate file existence, use context managers, specify encoding, handle expected exceptions, and avoid overwriting files accidentally.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.

8.5 Common mistakes

Typical errors include using w when a should be used, forgetting encoding, assuming every file exists, ignoring malformed CSV/JSON, and catching Exception too broadly.

Step-by-step:
  1. Identify the file type and the operation you need.
  2. Select the correct file mode and encoding.
  3. Open the file using a context manager when possible.
  4. Perform the read/write/process operation.
  5. Handle expected errors and verify the result.
HANDS-ON PRACTICE

30 Coding Questions

Try each problem yourself first, then open the step-by-step solution.

Q01

Create a text file and write a message.

Step 1: Identify the file operation required.
Step 2: Choose the correct file mode and safe context-manager pattern.
Step 3: Perform the operation and process the result.
Step 4: Run the code and verify the file contents/output.
with open("message.txt", "w", encoding="utf-8") as file:
    file.write("Hello Python")
Q02

Read the complete contents of a text file.

Step 1: Identify the file operation required.
Step 2: Choose the correct file mode and safe context-manager pattern.
Step 3: Perform the operation and process the result.
Step 4: Run the code and verify the file contents/output.
with open("message.txt", "r", encoding="utf-8") as file:
    content = file.read()

print(content)
Q03

Read a file line by line.

Step 1: Identify the file operation required.
Step 2: Choose the correct file mode and safe context-manager pattern.
Step 3: Perform the operation and process the result.
Step 4: Run the code and verify the file contents/output.
with open("message.txt", "r", encoding="utf-8") as file:
    for line in file:
        print(line.strip())
Q04

Read only the first line.

Step 1: Identify the file operation required.
Step 2: Choose the correct file mode and safe context-manager pattern.
Step 3: Perform the operation and process the result.
Step 4: Run the code and verify the file contents/output.
with open("message.txt", "r", encoding="utf-8") as file:
    print(file.readline().strip())
Q05

Read all lines into a list.

Step 1: Identify the file operation required.
Step 2: Choose the correct file mode and safe context-manager pattern.
Step 3: Perform the operation and process the result.
Step 4: Run the code and verify the file contents/output.
with open("message.txt", "r", encoding="utf-8") as file:
    lines = file.readlines()

print(lines)
Q06

Append a new line to a file.

Step 1: Identify the file operation required.
Step 2: Choose the correct file mode and safe context-manager pattern.
Step 3: Perform the operation and process the result.
Step 4: Run the code and verify the file contents/output.
with open("message.txt", "a", encoding="utf-8") as file:
    file.write("\nThis is a new line.")
Q07

Write multiple lines using writelines().

Step 1: Identify the file operation required.
Step 2: Choose the correct file mode and safe context-manager pattern.
Step 3: Perform the operation and process the result.
Step 4: Run the code and verify the file contents/output.
lines = ["Python\n", "SQL\n", "Power BI\n"]

with open("courses.txt", "w", encoding="utf-8") as file:
    file.writelines(lines)
Q08

Count the number of lines in a file.

Step 1: Identify the file operation required.
Step 2: Choose the correct file mode and safe context-manager pattern.
Step 3: Perform the operation and process the result.
Step 4: Run the code and verify the file contents/output.
with open("courses.txt", "r", encoding="utf-8") as file:
    count = sum(1 for line in file)

print("Lines:", count)
Q09

Count words in a text file.

Step 1: Identify the file operation required.
Step 2: Choose the correct file mode and safe context-manager pattern.
Step 3: Perform the operation and process the result.
Step 4: Run the code and verify the file contents/output.
with open("message.txt", "r", encoding="utf-8") as file:
    text = file.read()

print("Words:", len(text.split()))
Q10

Count a specific word in a file.

Step 1: Identify the file operation required.
Step 2: Choose the correct file mode and safe context-manager pattern.
Step 3: Perform the operation and process the result.
Step 4: Run the code and verify the file contents/output.
with open("message.txt", "r", encoding="utf-8") as file:
    text = file.read().lower()

print(text.split().count("python"))
Q11

Use tell() and seek().

Step 1: Identify the file operation required.
Step 2: Choose the correct file mode and safe context-manager pattern.
Step 3: Perform the operation and process the result.
Step 4: Run the code and verify the file contents/output.
with open("message.txt", "r", encoding="utf-8") as file:
    print("Start:", file.tell())
    print(file.read(5))
    print("After read:", file.tell())
    file.seek(0)
    print("Again:", file.read(5))
Q12

Copy text from one file to another.

Step 1: Identify the file operation required.
Step 2: Choose the correct file mode and safe context-manager pattern.
Step 3: Perform the operation and process the result.
Step 4: Run the code and verify the file contents/output.
with open("message.txt", "r", encoding="utf-8") as source:
    content = source.read()

with open("backup.txt", "w", encoding="utf-8") as target:
    target.write(content)
Q13

Handle a missing file safely.

Step 1: Identify the file operation required.
Step 2: Choose the correct file mode and safe context-manager pattern.
Step 3: Perform the operation and process the result.
Step 4: Run the code and verify the file contents/output.
try:
    with open("missing.txt", "r", encoding="utf-8") as file:
        print(file.read())
except FileNotFoundError:
    print("File not found")
Q14

Create a CSV file using csv.writer().

Step 1: Identify the file operation required.
Step 2: Choose the correct file mode and safe context-manager pattern.
Step 3: Perform the operation and process the result.
Step 4: Run the code and verify the file contents/output.
import csv

rows = [
    ["ID", "Name", "Marks"],
    [1, "Ravi", 85],
    [2, "Anita", 92]
]

with open("students.csv", "w", newline="", encoding="utf-8") as file:
    writer = csv.writer(file)
    writer.writerows(rows)
Q15

Read a CSV file using csv.reader().

Step 1: Identify the file operation required.
Step 2: Choose the correct file mode and safe context-manager pattern.
Step 3: Perform the operation and process the result.
Step 4: Run the code and verify the file contents/output.
import csv

with open("students.csv", "r", newline="", encoding="utf-8") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)
Q16

Read CSV records using DictReader.

Step 1: Identify the file operation required.
Step 2: Choose the correct file mode and safe context-manager pattern.
Step 3: Perform the operation and process the result.
Step 4: Run the code and verify the file contents/output.
import csv

with open("students.csv", "r", newline="", encoding="utf-8") as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(row["Name"], row["Marks"])
Q17

Create a CSV file using DictWriter.

Step 1: Identify the file operation required.
Step 2: Choose the correct file mode and safe context-manager pattern.
Step 3: Perform the operation and process the result.
Step 4: Run the code and verify the file contents/output.
import csv

records = [
    {"ID": 1, "Name": "Ravi", "Marks": 85},
    {"ID": 2, "Name": "Anita", "Marks": 92}
]

with open("students2.csv", "w", newline="", encoding="utf-8") as file:
    writer = csv.DictWriter(file, fieldnames=["ID", "Name", "Marks"])
    writer.writeheader()
    writer.writerows(records)
Q18

Convert a Python dictionary to a JSON string.

Step 1: Identify the file operation required.
Step 2: Choose the correct file mode and safe context-manager pattern.
Step 3: Perform the operation and process the result.
Step 4: Run the code and verify the file contents/output.
import json

student = {"name": "Ravi", "age": 21, "course": "Python"}
text = json.dumps(student, indent=2)

print(text)
Q19

Convert a JSON string to a Python dictionary.

Step 1: Identify the file operation required.
Step 2: Choose the correct file mode and safe context-manager pattern.
Step 3: Perform the operation and process the result.
Step 4: Run the code and verify the file contents/output.
import json

text = '{"name": "Ravi", "age": 21}'
student = json.loads(text)

print(student["name"])
Q20

Write a Python dictionary to a JSON file.

Step 1: Identify the file operation required.
Step 2: Choose the correct file mode and safe context-manager pattern.
Step 3: Perform the operation and process the result.
Step 4: Run the code and verify the file contents/output.
import json

data = {
    "name": "Anita",
    "skills": ["Python", "SQL"]
}

with open("student.json", "w", encoding="utf-8") as file:
    json.dump(data, file, indent=2)
Q21

Read a JSON file.

Step 1: Identify the file operation required.
Step 2: Choose the correct file mode and safe context-manager pattern.
Step 3: Perform the operation and process the result.
Step 4: Run the code and verify the file contents/output.
import json

with open("student.json", "r", encoding="utf-8") as file:
    data = json.load(file)

print(data)
Q22

Update a JSON value and save it.

Step 1: Identify the file operation required.
Step 2: Choose the correct file mode and safe context-manager pattern.
Step 3: Perform the operation and process the result.
Step 4: Run the code and verify the file contents/output.
import json

with open("student.json", "r", encoding="utf-8") as file:
    data = json.load(file)

data["name"] = "Anita Sharma"

with open("student.json", "w", encoding="utf-8") as file:
    json.dump(data, file, indent=2)
Q23

Handle invalid integer input with try/except.

Step 1: Identify the file operation required.
Step 2: Choose the correct file mode and safe context-manager pattern.
Step 3: Perform the operation and process the result.
Step 4: Run the code and verify the file contents/output.
try:
    age = int(input("Enter age: "))
    print("Age:", age)
except ValueError:
    print("Please enter a valid integer.")
Q24

Handle division by zero.

Step 1: Identify the file operation required.
Step 2: Choose the correct file mode and safe context-manager pattern.
Step 3: Perform the operation and process the result.
Step 4: Run the code and verify the file contents/output.
try:
    a = int(input("Enter numerator: "))
    b = int(input("Enter denominator: "))
    print(a / b)
except ZeroDivisionError:
    print("Cannot divide by zero.")
except ValueError:
    print("Enter numbers only.")
Q25

Use try/except/else/finally.

Step 1: Identify the file operation required.
Step 2: Choose the correct file mode and safe context-manager pattern.
Step 3: Perform the operation and process the result.
Step 4: Run the code and verify the file contents/output.
try:
    number = int(input("Enter a number: "))
except ValueError:
    print("Invalid input")
else:
    print("Square:", number ** 2)
finally:
    print("Program finished")
Q26

Raise an exception for an invalid age.

Step 1: Identify the file operation required.
Step 2: Choose the correct file mode and safe context-manager pattern.
Step 3: Perform the operation and process the result.
Step 4: Run the code and verify the file contents/output.
age = int(input("Enter age: "))

if age < 0:
    raise ValueError("Age cannot be negative")

print("Valid age:", age)
Q27

Create a custom exception.

Step 1: Identify the file operation required.
Step 2: Choose the correct file mode and safe context-manager pattern.
Step 3: Perform the operation and process the result.
Step 4: Run the code and verify the file contents/output.
class InsufficientBalanceError(Exception):
    pass

balance = 1000
withdraw = 1500

if withdraw > balance:
    raise InsufficientBalanceError("Insufficient balance")
Q28

Build a CSV student average calculator.

Step 1: Identify the file operation required.
Step 2: Choose the correct file mode and safe context-manager pattern.
Step 3: Perform the operation and process the result.
Step 4: Run the code and verify the file contents/output.
import csv

total = 0
count = 0

with open("students.csv", "r", newline="", encoding="utf-8") as file:
    reader = csv.DictReader(file)
    for row in reader:
        total += float(row["Marks"])
        count += 1

print("Average:", total / count if count else 0)
Q29

Build a JSON-based contact book.

Step 1: Identify the file operation required.
Step 2: Choose the correct file mode and safe context-manager pattern.
Step 3: Perform the operation and process the result.
Step 4: Run the code and verify the file contents/output.
import json

contacts = {
    "Ravi": "9876543210",
    "Anita": "9123456780"
}

with open("contacts.json", "w", encoding="utf-8") as file:
    json.dump(contacts, file, indent=2)

with open("contacts.json", "r", encoding="utf-8") as file:
    contacts = json.load(file)

print(contacts.get("Ravi"))
Q30

Build a simple text log system.

Step 1: Identify the file operation required.
Step 2: Choose the correct file mode and safe context-manager pattern.
Step 3: Perform the operation and process the result.
Step 4: Run the code and verify the file contents/output.
from datetime import datetime

message = input("Enter log message: ")

with open("app.log", "a", encoding="utf-8") as file:
    timestamp = datetime.now().isoformat(timespec="seconds")
    file.write(f"{timestamp} - {message}\n")

print("Log saved.")
KNOWLEDGE CHECK

30 Theory Questions with Answers

Use these for revision, interviews, and classroom practice.

Q01

What is file handling?

Answer: File handling is the process of reading, writing, creating, updating, and managing files from a program.
Q02

Why are files used in Python programs?

Answer: Files provide persistent storage so data can remain available after the program stops.
Q03

What does open() do?

Answer: open() opens a file and returns a file object that can be used for reading or writing.
Q04

What is the default mode of open()?

Answer: The default mode is r, which opens the file for reading text.
Q05

What does r mode mean?

Answer: r opens an existing file for reading and raises FileNotFoundError if it does not exist.
Q06

What does w mode mean?

Answer: w opens a file for writing, creating it if needed and truncating existing content.
Q07

What does a mode mean?

Answer: a opens a file for appending and places new writes at the end of the file.
Q08

What does x mode mean?

Answer: x creates a new file and fails if the file already exists.
Q09

What does b mean in a file mode?

Answer: b selects binary mode, allowing bytes to be read or written.
Q10

Why use with open()?

Answer: The with statement automatically closes the file and manages the resource safely.
Q11

What does read() do?

Answer: read() returns file content as a string in text mode, optionally limited by a size.
Q12

What does readline() do?

Answer: readline() reads one line from the current file position.
Q13

What does readlines() do?

Answer: readlines() returns the remaining lines as a list.
Q14

What does tell() do?

Answer: tell() returns the current file position.
Q15

What does seek() do?

Answer: seek() changes the current file position.
Q16

What does write() return?

Answer: write() returns the number of characters written in text mode.
Q17

What is CSV?

Answer: CSV is a simple tabular text format in which records are represented as rows and fields are separated by a delimiter, commonly a comma.
Q18

What is csv.reader()?

Answer: It reads CSV rows and returns each row as a sequence of values.
Q19

What is csv.writer()?

Answer: It writes rows to a CSV file while handling CSV formatting and quoting.
Q20

What is DictReader?

Answer: DictReader maps each CSV row to a dictionary using the header names as keys.
Q21

What is JSON?

Answer: JSON is a text-based format used to represent structured data and exchange information between systems.
Q22

What is the difference between dumps() and dump()?

Answer: dumps() converts a Python object to a JSON string, while dump() writes the JSON representation directly to a file.
Q23

What is the difference between loads() and load()?

Answer: loads() converts a JSON string to a Python object, while load() reads JSON from a file.
Q24

What is an exception?

Answer: An exception is an event during execution that interrupts normal program flow.
Q25

What is try/except?

Answer: try contains code that may fail, while except handles a specified exception.
Q26

What is else in exception handling?

Answer: else runs when the try block completes successfully without an exception.
Q27

What is finally?

Answer: finally runs regardless of whether an exception occurs and is useful for cleanup.
Q28

What does raise do?

Answer: raise deliberately triggers an exception.
Q29

What is a custom exception?

Answer: It is a programmer-defined exception class, usually derived from Exception, representing an application-specific error.
Q30

Why should exceptions be specific?

Answer: Handling specific expected exceptions makes programs safer and avoids hiding unrelated programming errors.