Registry Synced

Week 10: CSV Processing & Exception Handling

4561 words
23 min read
2026-09-12

Reading compass

Now · TL;DR

Programming in Python — Week 10: CSV Processing & Exception Handling

The official IITM syllabus lists Week 10: File Operations (Continued). The syllabus file does not provide finer subtopics, so the material below is a standard continuation of Python file handling and file-processing workflows, not a claim about exact lecture ordering.

TL;DR

Week 9 introduced:
text
open
read
write
append
parse
close
Week 10 is best thought of as:
text
file
↓
parse records
↓
validate
↓
transform
↓
aggregate
↓
write structured output
The main skills are:
  • processing files record-by-record
  • maintaining running summaries
  • multiple input/output files
  • structured records
  • headers
  • malformed data
  • copying/filtering/transforming files
  • file position
  • read/write mode details
  • exception-safe file handling
  • turning file data into Python collections and back

1. File processing is usually a pipeline

A realistic file task often looks like:
text
INPUT FILE
   ↓
read one record
   ↓
parse fields
   ↓
convert datatypes
   ↓
validate
   ↓
process
   ↓
update result
   ↓
OUTPUT FILE
This is the same collection-processing logic from Weeks 6–8, except data now arrives from persistent storage.

2. Record-by-record processing

Suppose file:
text
A,80
B,90
C,70
Each line is one record:
text
name,mark
A clean loop:
python
with open("marks.txt", "r") as f:
    for line in f:
        name, mark = line.strip().split(",")
        mark = int(mark)

        # process record

3. Keep parsing separate from processing

Conceptually separate:
text
raw line
↓
parsed fields
↓
typed values
↓
algorithm
For example:
python
line = "A,80\n"

name, mark_text = line.strip().split(",")
mark = int(mark_text)
Now:
text
name = "A"
mark = 80
Only after this should numerical logic begin.

4. Header handling

Suppose:
text
name,mark
A,80
B,90
The first row is a header.
One simple pattern:
python
with open("marks.txt", "r") as f:
    header = f.readline()

    for line in f:
        ...
This consumes the header once.

5. Why header handling matters

If you attempt:
python
name, mark = "name,mark".split(",")
mark = int(mark)
then Python tries:
python
int("mark")
which fails.
So metadata rows must be treated differently from data rows.

6. Skip blank lines

A robust processing loop may do:
python
with open("data.txt", "r") as f:
    for line in f:
        line = line.strip()

        if line == "":
            continue

        # parse real data
This avoids accidental conversion of empty strings.

7. Validate field count

Suppose expected:
text
name,mark
Then:
python
parts = line.strip().split(",")
should have:
22
fields.
You can conceptually check:
python
if len(parts) != 2:
    ...
before unpacking.

8. Why validation matters

Malformed line:
text
A,80,Delhi
contains three fields.
This fails:
python
name, mark = line.split(",")
because two variables cannot receive three values.

9. Type validation

Even if field count is correct:
text
A,eighty
still fails when converted:
python
int("eighty")
So file validity has multiple layers:
text
correct structure
+
correct datatypes
+
correct value ranges

10. Exception handling intuition

Python can handle predictable failures using:
python
try:
    ...
except:
    ...
Example:
python
try:
    mark = int(mark_text)
except ValueError:
    print("Invalid mark")
This is useful when external file data may be malformed.

11. Prefer specific exceptions

Instead of:
python
except:
prefer when possible:
python
except ValueError:
This says exactly what kind of failure you intend to handle.
It avoids accidentally hiding unrelated bugs.

12. Parsing safely

Example:
python
with open("marks.txt", "r") as f:
    for line in f:
        parts = line.strip().split(",")

        if len(parts) != 2:
            continue

        name, mark_text = parts

        try:
            mark = int(mark_text)
        except ValueError:
            continue
Now only valid two-field numerical records proceed.

13. Range validation after conversion

Suppose valid marks satisfy:
0≤mark≤100.0\leq mark\leq100.
After parsing:
python
if not 0 <= mark <= 100:
    continue
So validation order is:
text
structure
↓
datatype
↓
value range

14. Count valid vs invalid records

python
valid = 0
invalid = 0
Then for each row:
python
if bad_record:
    invalid += 1
else:
    valid += 1
This is useful when processing imperfect datasets.

15. Aggregate while reading

You do not always need to store all records.
Example:
python
total = 0
count = 0

with open("marks.txt", "r") as f:
    for line in f:
        mark = int(line.strip())
        total += mark
        count += 1
This computes summaries in one pass.

16. Streaming average

At the end:
python
if count > 0:
    average = total / count
Memory usage does not grow with number of records because we keep only:
text
total
count
rather than the entire dataset.

17. Streaming maximum

python
maximum = None

with open("numbers.txt", "r") as f:
    for line in f:
        x = float(line)

        if maximum is None or x > maximum:
            maximum = x
Only one running state variable is needed.

18. Preserve associated record

Suppose file:
text
A,80
B,95
C,70
To find best student:
python
best_name = None
best_mark = None

with open("marks.txt", "r") as f:
    for line in f:
        name, mark_text = line.strip().split(",")
        mark = int(mark_text)

        if best_mark is None or mark > best_mark:
            best_name = name
            best_mark = mark
Keep both the maximum value and associated identity.

19. Frequency analysis from files

Suppose file:
text
red
blue
red
green
red
blue
Use:
python
freq = {}

with open("colors.txt", "r") as f:
    for line in f:
        color = line.strip()
        freq[color] = freq.get(color, 0) + 1
Result:
python
{
    "red": 3,
    "blue": 2,
    "green": 1
}

20. Grouping records from files

File:
text
A,10
B,5
A,7
B,2
Grouped totals:
python
totals = {}

with open("data.txt", "r") as f:
    for line in f:
        name, value = line.strip().split(",")
        value = int(value)

        totals[name] = totals.get(name, 0) + value
Final:
python
{
    "A": 17,
    "B": 7
}

21. Group into lists

If you need all values:
python
groups = {}

with open("data.txt", "r") as f:
    for line in f:
        name, value = line.strip().split(",")
        value = int(value)

        if name not in groups:
            groups[name] = []

        groups[name].append(value)
Now:
python
{
    "A": [10, 7],
    "B": [5, 2]
}

22. Multiple-pass processing

Sometimes one pass is not enough.
Example:
  1. compute average
  2. count how many values exceed average
You may:
  • read file twice
  • store values in memory
  • or reopen the file

23. Reopen for second pass

python
total = 0
count = 0

with open("numbers.txt", "r") as f:
    for line in f:
        total += float(line)
        count += 1

average = total / count

above = 0

with open("numbers.txt", "r") as f:
    for line in f:
        if float(line) > average:
            above += 1
This uses two passes without storing every value.

24. Why reopening works

At the end of the first pass, file cursor is at EOF.
Opening the file again starts a fresh file object at the beginning.

25. Alternative: store data once

python
values = []

with open("numbers.txt", "r") as f:
    for line in f:
        values.append(float(line))
Then:
python
average = sum(values) / len(values)

above = sum(1 for x in values if x > average)
This uses more memory but avoids a second disk read.

26. Trade-off: memory vs rereading

Two-pass file:
text
less memory
+
more I/O
Store-all approach:
text
more memory
+
easier repeated analysis
Algorithm design often involves such trade-offs.

27. Read/write mode "r+"

Python supports combined modes such as:
python
"r+"
which permit reading and writing.
However, mixing reading and writing around one file cursor requires more care.
For introductory work, separate input and output files are often clearer.

28. "w+" intuition

"w+" allows reading and writing but also truncates the file when opened.
So it can erase previous contents just like "w".
Do not use it casually.

29. "a+" intuition

"a+" allows appending plus reading.
Writes go to the end.
Again, mixed read/write modes are more subtle than simple "r", "w", "a".

30. File cursor after writing

If you write to a file and then want to read from it using the same object, cursor position matters.
Example:
python
f.write("hello")
leaves position after the written text.
A subsequent read begins from that current position unless repositioned.

31. tell()

Python:
python
f.tell()
reports the current file position.
At a conceptual level:
where is the cursor now?
This helps explain why reads can return nothing after earlier operations.

32. seek()

python
f.seek(0)
moves the cursor back to the beginning.
Useful in combined read/write workflows.
For basic text processing, reopening the file is often conceptually simpler.

33. Input file + output file

A clean transform pattern:
python
with open("input.txt", "r") as src:
    with open("output.txt", "w") as dst:
        for line in src:
            ...
            dst.write(...)
This separates responsibilities clearly.

34. Filter file

Input:
text
5
-2
7
0
-1
Write only positives:
python
with open("input.txt", "r") as src:
    with open("positive.txt", "w") as dst:
        for line in src:
            x = int(line)

            if x > 0:
                dst.write(f"{x}\n")
Output:
text
5
7

35. Transform file

Input:
text
1
2
3
Output squares:
python
with open("input.txt", "r") as src:
    with open("squares.txt", "w") as dst:
        for line in src:
            x = int(line)
            dst.write(f"{x ** 2}\n")
Result:
text
1
4
9

36. Normalize text file

python
with open("input.txt", "r") as src:
    with open("output.txt", "w") as dst:
        for line in src:
            cleaned = line.strip().lower()

            if cleaned != "":
                dst.write(cleaned + "\n")
This:
  • trims whitespace
  • converts case
  • removes blank lines

37. Merge files

Suppose:
text
part1.txt
part2.txt
Conceptually:
python
with open("combined.txt", "w") as dst:
    with open("part1.txt", "r") as f:
        for line in f:
            dst.write(line)

    with open("part2.txt", "r") as f:
        for line in f:
            dst.write(line)
Output contains first file followed by second.

38. Compare two files conceptually

You might:
  1. read both
  2. compare their contents
Simple:
python
with open("a.txt", "r") as fa:
    a = fa.read()

with open("b.txt", "r") as fb:
    b = fb.read()

print(a == b)
This tests exact textual equality.

39. Exact equality includes whitespace

These are different:
text
hello
and:
text
hello 
because one contains an extra space.
Likewise final newline differences can matter.
Normalization may be needed if formatting differences should be ignored.

40. Copy while changing selected records

Suppose:
text
A,80
B,90
and we want to add 5 marks:
python
with open("input.txt", "r") as src:
    with open("output.txt", "w") as dst:
        for line in src:
            name, mark = line.strip().split(",")
            mark = int(mark) + 5

            dst.write(f"{name},{mark}\n")

41. Do not overwrite input prematurely

A dangerous idea:
python
open("data.txt", "w")
before you finish reading old data.txt.
That truncates the source.
Safer approach:
text
read source
→ write separate output
→ optionally replace later

42. Temporary-file pattern conceptually

For updating a file safely:
text
original file
↓
read
↓
write modified data to temporary file
↓
replace original only after success
This avoids destroying source data halfway through processing.

43. Append logs

Append mode is ideal for event history:
python
with open("log.txt", "a") as f:
    f.write("Task completed\n")
Repeated executions accumulate history.

44. Structured logging

Instead of:
text
something happened
write predictable fields:
text
2026-01-01,INFO,Task completed
Structured records are easier to parse later.

45. Writing dictionaries

Suppose:
python
freq = {
    "cat": 3,
    "dog": 2
}
Write:
python
with open("freq.txt", "w") as f:
    for word, count in freq.items():
        f.write(f"{word},{count}\n")

46. Deterministic output ordering

Dictionary iteration follows Python's mapping order semantics, but if a problem explicitly requires sorted output, sort it:
python
for word in sorted(freq):
    f.write(f"{word},{freq[word]}\n")
Now output is sorted by key.

47. Sort by frequency

python
items = sorted(
    freq.items(),
    key=lambda pair: pair[1],
    reverse=True
)

with open("freq.txt", "w") as f:
    for word, count in items:
        f.write(f"{word},{count}\n")
This connects Week 8 sorting with file output.

48. Parse key-value configuration

Suppose:
text
theme=dark
volume=80
language=en
You can parse:
python
config = {}

with open("config.txt", "r") as f:
    for line in f:
        key, value = line.strip().split("=", 1)
        config[key] = value
Result:
python
{
    "theme": "dark",
    "volume": "80",
    "language": "en"
}

49. Why split("=", 1)?

Without the second argument, every = is treated as a separator.
Using:
python
split("=", 1)
means:
split at most once.
Useful when the value might itself contain the delimiter.

50. Parsing is format-dependent

Different files need different parsers.
Examples:
text
one value per line
comma-separated
tab-separated
key=value
free-form text
There is no universal .split() pattern for all files.
First understand the data format.

51. Tabs

Tab character:
python
"\t"
A tab-separated line can be parsed with:
python
line.strip().split("\t")
Same idea as comma-separated text.

52. Whitespace-separated data

If fields are separated by arbitrary whitespace:
python
parts = line.split()
is useful because it handles runs of spaces/tabs.
Example:
text
A    80    90
can become:
python
["A", "80", "90"]

53. strip().split() vs split()

Often:
python
line.split()
already ignores surrounding whitespace and splits on whitespace.
So:
python
line.strip().split()
may be redundant in simple whitespace-delimited cases.
Understand what each method contributes.

54. Exceptions from file opening

This:
python
open("missing.txt", "r")
can raise:
text
FileNotFoundError
A specific handler:
python
try:
    with open("missing.txt", "r") as f:
        ...
except FileNotFoundError:
    print("File missing")

55. Permission failures

A file may exist but still not be readable/writable due to permissions.
So external resources can fail for reasons unrelated to algorithm logic.
This is a general lesson:
I/O introduces environmental failure modes\boxed{ \text{I/O introduces environmental failure modes} }

56. with still matters during exceptions

If an exception occurs inside:
python
with open(...) as f:
Python still performs file cleanup when leaving the context.
This is one reason with is preferred.

57. File operation vs parsing error

Distinguish:

File error

Could not open/read file.

Parsing error

File opened, but content format is wrong.

Logical error

File and format are valid, but algorithm computes wrong result.
These are separate debugging layers.

58. Example layered debugging

Suppose average calculation fails.
Ask:
  1. Did file open?
  2. Were lines actually read?
  3. Did conversion succeed?
  4. Was header skipped?
  5. Were blank lines handled?
  6. Were totals/counts updated correctly?
  7. Was division done after loop?
This isolates the failure source.

59. Read-once iterables intuition

File iteration naturally moves forward.
python
for line in f:
    ...
consumes lines.
After completion, another loop over the same file object sees EOF unless cursor is reset or file reopened.

60. This differs from a list

A list:
python
values = [1, 2, 3]
can easily be looped repeatedly:
python
for x in values:
    ...

for x in values:
    ...
The list itself is still present in memory.
A file object has mutable cursor state.

61. Load into list when repeated traversal is useful

python
with open("data.txt", "r") as f:
    lines = f.readlines()
Now lines is a list and can be traversed repeatedly.
Trade-off:
text
convenience
↔
memory usage

62. Generator-style processing intuition

Line-by-line file processing is an example of lazy/streaming behavior:
text
get next item
process it
get next item
...
You need not materialize the entire dataset first.

63. Huge-file reasoning

If a file contains millions of records:
python
f.read()
may consume substantial memory.
Instead:
python
for line in f:
can process incrementally.
This is one reason iteration abstractions matter.

64. Count unique records

python
seen = set()

with open("data.txt", "r") as f:
    for line in f:
        value = line.strip()
        seen.add(value)

print(len(seen))
This combines files with sets.

65. Detect duplicates

python
seen = set()
duplicates = set()

with open("data.txt", "r") as f:
    for line in f:
        value = line.strip()

        if value in seen:
            duplicates.add(value)
        else:
            seen.add(value)
At end:
python
duplicates
contains repeated values.

66. Preserve duplicate order

If order matters:
python
seen = set()
duplicates = []

for value in data:
    if value in seen and value not in duplicates:
        duplicates.append(value)
    else:
        seen.add(value)
Collection choice changes semantics.

67. Index line numbers with enumerate()

python
with open("data.txt", "r") as f:
    for line_number, line in enumerate(f, start=1):
        print(line_number, line)
This is useful when reporting malformed lines.

68. Example error reporting

python
with open("data.txt", "r") as f:
    for line_number, line in enumerate(f, start=1):
        parts = line.strip().split(",")

        if len(parts) != 2:
            print("Invalid line:", line_number)
Now diagnostics identify where the issue occurred.

69. Multiple input files

Suppose one file contains student names and another contains marks.
You might read both into collections and combine them.
But parallel files can create alignment problems similar to parallel lists.
Whenever possible, related fields are often safer in the same record.

70. One record per line is a strong pattern

Example:
text
student_id,name,mark
keeps related information together.
This reduces risk of losing synchronization across separate files.

71. File record invariant

If your algorithm assumes:
text
each valid line has exactly 3 fields
that is an invariant/format contract.
The parser should either:
  • trust guaranteed input, or
  • validate before processing
depending on problem assumptions.

72. Reformat data

Input:
text
A 80
B 90
Output:
text
A,80
B,90
Program:
python
with open("input.txt", "r") as src:
    with open("output.txt", "w") as dst:
        for line in src:
            name, mark = line.split()
            dst.write(f"{name},{mark}\n")
This changes representation without changing underlying information.

73. Selection while copying

Input file can be treated like a stream of records.
Example:
python
if mark >= 40:
    dst.write(...)
This is exactly the filter pattern from collections.

74. Transformation while copying

python
mark = min(mark + 5, 100)
then write.
This is exactly the transform pattern.

75. Grouping while reading

python
groups[key].append(value)
This is the group pattern.
So file processing adds no new algorithmic category; it connects old categories to external data.

76. Reduce while reading

Examples:
text
sum
count
min
max
frequency
These are reductions/aggregations.
You can calculate them without storing every row.

77. File operation pattern library

Count rows

python
count += 1

Sum field

python
total += value

Frequency

python
freq[x] = freq.get(x, 0) + 1

Group

python
groups[key].append(value)

Filter to output

python
if condition:
    dst.write(...)

Transform to output

python
dst.write(format(transform(record)))

Common mistake: forgetting header changes counts
If file has:
text
name,mark
A,80
B,90
then raw line count is:
3.3.
But number of student records is:
2.2.
Understand whether metadata counts as data.

Common mistake: count blank lines
A blank line may not represent a record.
If required, check:
python
if line.strip() == "":
    continue
before incrementing count.

Common mistake: strip destroys meaningful delimiter spaces
Suppose fixed-width file relies on exact spaces.
Then blindly using:
python
strip()
can alter record structure.
Parsing must match format.

Common mistake: mutate dictionary during iteration
If reading file builds a dictionary and later you iterate over it, avoid adding/removing keys during that same direct iteration unless you specifically understand the behavior.
Safer:
python
result = {}
or iterate over a snapshot.

Common mistake: overwrite duplicate dictionary key unintentionally
Input:
text
A,80
A,90
This:
python
marks[name] = mark
leaves:
python
{"A": 90}
If both values matter, use:
python
groups[name].append(mark)
or aggregate them.

Common mistake: assume order-independent output
If a grader expects sorted output, explicitly sort.
Example:
python
for key in sorted(d):
Do not assume arbitrary collection traversal matches required output order.

Common mistake: file already exhausted
python
for line in f:
    ...

for line in f:
    ...
Second loop may execute zero times.
Either:
python
f.seek(0)
or reopen the file.

Common mistake: forgot newline while writing records
Without:
python
"\n"
records can run together:
text
A,80B,90C,70
Formatting separators are part of the data format.

Common mistake: extra newline
If line already includes newline:
python
dst.write(line + "\n")
can add an extra blank line.
Know whether your string already contains the separator.

Common mistake: write before validation
Safer processing order:
text
read
→ parse
→ validate
→ transform
→ write
not:
text
read
→ immediately write
→ discover later it was invalid

Common mistake: open output inside loop
Wrong:
python
for item in values:
    with open("out.txt", "w") as f:
        f.write(...)
Every iteration reopens with "w" and truncates previous output.
Likely only the last record survives.

89. Correct output loop

python
with open("out.txt", "w") as f:
    for item in values:
        f.write(...)
Open once.
Write many times.
Close once.

Common mistake: reopening append unintentionally
Opening repeatedly with:
python
"a"
may be valid, but it is unnecessary overhead if one open handle can remain active for the whole operation.
Prefer clear scope.

91. Trace multi-record aggregation

File:
text
A,3
B,4
A,5
C,2
B,1
Code:
python
totals = {}

for line in f:
    key, value = line.strip().split(",")
    value = int(value)

    totals[key] = totals.get(key, 0) + value
Trace:
text
{}
A,3 → {"A":3}
B,4 → {"A":3,"B":4}
A,5 → {"A":8,"B":4}
C,2 → {"A":8,"B":4,"C":2}
B,1 → {"A":8,"B":5,"C":2}

92. Trace filter/write

Input:
text
5
-1
8
0
Program writes values satisfying:
python
x > 0
Output:
text
5
8
The output file itself is the accumulated result.

93. File processing as state machine

At any point, program state may include:
text
current file position
current line
parsed fields
running counters
running dictionary
output written so far
Tracing file programs means tracking both:
program state+file state\boxed{ \text{program state} + \text{file state} }

94. File state includes cursor position

For read questions, note:
text
which lines have already been consumed?
For write questions, note:
text
what has already been written?
This avoids confusion in multi-step I/O traces.

95. A complete processing example

Input:
text
name,mark
A,80
B,35
C,91
D,50
Goal:
  • skip header
  • keep passing marks ≥40\geq40
  • write name,mark
  • calculate passing average
python
total = 0
count = 0

with open("marks.txt", "r") as src:
    with open("passed.txt", "w") as dst:
        src.readline()

        for line in src:
            name, mark_text = line.strip().split(",")
            mark = int(mark_text)

            if mark >= 40:
                dst.write(f"{name},{mark}\n")
                total += mark
                count += 1

if count > 0:
    print(total / count)

96. Result of example

Passing students:
text
A,80
C,91
D,50
Average:
80+91+503=2213≈73.67.\frac{80+91+50}{3} = \frac{221}{3} \approx73.67.
One file traversal performed:
  • parsing
  • filtering
  • output
  • aggregation

97. File pipelines prepare you for Pandas

Manual Week 9–10 code often looks like:
text
open
loop through records
parse
filter
aggregate
Later libraries such as Pandas provide higher-level abstractions for the same broad data-processing tasks.
Understanding manual processing first makes those abstractions easier to reason about.

98. Compact Week 10 cheat sheet

python
## parse record
name, value = line.strip().split(",")
value = int(value)
python
## skip bad/blank record
if line.strip() == "":
    continue
python
## two-pass reading
with open(path) as f:
    ...

with open(path) as f:
    ...
python
## copy/transform
with open(src_path, "r") as src:
    with open(dst_path, "w") as dst:
        for line in src:
            ...
python
## report line numbers
for line_no, line in enumerate(f, start=1):
    ...
python
## error handling
try:
    x = int(text)
except ValueError:
    ...

99. File-problem solving checklist

For any file problem, determine:
  1. What is the input file format?
  2. Is there a header?
  3. Can blank lines occur?
  4. What delimiter is used?
  5. Which fields need datatype conversion?
  6. What constitutes a valid record?
  7. Should invalid records be skipped or reported?
  8. Do you need all data in memory?
  9. Can you process one row at a time?
  10. Is one pass enough?
  11. What state must persist across records?
  12. Is output fresh or appended?
  13. What exact output format is required?
  14. Does ordering matter?

100. Week 9 → Week 10 progression

Week 9:
text
How do I read and write files?
Week 10:
text
How do I build reliable algorithms around file data?
The conceptual progression is:
basic I/O→structured processing→data pipeline\boxed{ \text{basic I/O} \rightarrow \text{structured processing} \rightarrow \text{data pipeline} }

101. What you should actually master

By the end of Python Week 10, you should be able to:
  1. Parse structured file records.
  2. Handle headers.
  3. Skip blank lines.
  4. Validate field counts.
  5. Convert fields to appropriate types.
  6. Understand basic exception handling for bad input.
  7. Aggregate file data in one pass.
  8. Find min/max while streaming.
  9. Preserve associated record information.
  10. Build frequency dictionaries from files.
  11. Group file records.
  12. Perform multiple-pass processing.
  13. Understand memory-vs-rereading trade-offs.
  14. Work with input and output files simultaneously.
  15. Filter records into a new file.
  16. Transform records into a new file.
  17. Merge/copy files conceptually.
  18. Understand file cursor state.
  19. Use seek()/reopening conceptually when rereading.
  20. Report line numbers with enumerate().
  21. Recognize malformed-data problems.
  22. Avoid destructive "w" mistakes.
  23. Avoid opening output inside a loop.
  24. Keep exact output formatting correct.
  25. Trace both program state and file state.
If these are comfortable, Programming in Python Week 10 is under control.

Quick Recall & Flashcards

Test your active recall before proceeding to practice problems. Format:
Question :: Answer.
  • Week 10 Diagnostic: In Python's csv module, what does csv.DictReader return for each row? :: Answer: B — csv.DictReader maps each row into a dictionary using the header row as keys.
  • Week 10 Diagnostic: Which block in a try-except-finally statement is ALWAYS executed regardless of whether an exception occurred? :: Answer: D — The finally block always executes, commonly used for cleanup actions like releasing resources.

Practice & Self-Check

Attempt these diagnostic questions to verify your operational understanding.
1

Question 1

In Python's csv module, what does csv.DictReader return for each row?
MCQ
3 Unit Assessment
A. A list of strings
B. A dictionary mapping column header names to field values
C. A tuple of integers
D. A Pandas DataFrame
2

Question 2

Which block in a try-except-finally statement is ALWAYS executed regardless of whether an exception occurred?
MCQ
3 Unit Assessment
A. try
B. except
C. else
D. finally
Document outline

Keep your place and jump directly to a heading.

Table of contents

No note selected

Open a chapter to see its outline, backlinks, and sources here.