November 16, 2026•5 min read

Python try/except/finally: Handling a Blank CSV Cell Without Losing the Total

A minutes total dies on one empty CSV cell and prints nothing, so the rows that parsed fine are lost with it. Wrapping the conversion in try with except ValueError skips the bad row, and finally prints the summary even when the file is missing.

Read in Indonesian

A short script sums the minutes in a CSV file and prints one line with the total. Then one cell is empty. The script dies with a traceback and prints nothing, so the rows it read correctly vanish with it. You lose the whole report over a single blank field.

Key takeaways

  • One blank cell raises ValueError and stops the run before the total is printed, so the rows that parsed fine are lost with it.
  • try around the single conversion and except ValueError skip that row, count it, and let the loop reach the end.
  • finally runs whether the block succeeded or raised, which is why the summary line prints before the missing-file error.
  • A bare except: also swallows sys.exit() and Ctrl-C, so name the exception you expect.

The crash

Save this as sessions.csv. The row for 2026-11-04 has an empty minutes field.

CSV
date,minutes
2026-11-03,20
2026-11-04,
2026-11-05,30

Save the starter script as totals.py. It takes the file path from the command line and adds up the minutes column. csv.DictReader hands you one dict per row with string values, so the script converts each value with int.

PYTHON
# totals.py
import csv
import sys

path = sys.argv[1]

total = 0
with open(path, newline="") as handle:
    for row in csv.DictReader(handle):
        total += int(row["minutes"])

print(f"total {total}")

Running it on the file ends in a traceback and exit status 1.

TEXT
$ python3 totals.py sessions.csv 2>&1 | tail -2
    total += int(row["minutes"])
ValueError: invalid literal for int() with base 10: ''

The last line names the problem. int("") has nothing to convert, so it raises ValueError. Nothing was printed before the traceback, so the two good rows printed nothing either.

The checker check_totals.py turns this failure into a number. It writes sessions.csv itself, runs totals.py in a child process, and counts the checks that pass.

PYTHON
# check_totals.py
import subprocess
import sys
from pathlib import Path

ROWS = """date,minutes
2026-11-03,20
2026-11-04,
2026-11-05,30
"""


def run(path):
    return subprocess.run([sys.executable, "totals.py", path], text=True, capture_output=True)


def report(results):
    for label, passed, detail in results:
        mark = "PASS" if passed else "FAIL"
        note = f"  <- {detail}" if detail and not passed else ""
        print(f"{mark}  {label}{note}")
    passed = [ok for _, ok, _ in results].count(True)
    print(f"\n{passed} of {len(results)} checks passed")


def main():
    path = Path("sessions.csv")
    path.write_text(ROWS)

    run_ok = run(str(path))
    crashed = run_ok.returncode != 0
    last = run_ok.stderr.strip().splitlines()[-1] if run_ok.stderr.strip() else ""

    results = [("the script finishes on a file with one blank field", not crashed, last)]
    if crashed:
        report(results)
        return 1

    out = run_ok.stdout
    lines = [line for line in out.splitlines() if line.strip()]

    results.append(("it prints the total of the rows it could read", "total 50" in out, out.strip()))
    results.append(("it says which row it skipped", "2026-11-04" in out, out.strip()))
    results.append(("it prints one line per skipped row", len(lines) == 2, str(lines)))

    run_missing = run("no_such_file.csv")
    results.append(("it still reports the summary when the file is missing", "read 0 rows" in run_missing.stdout, run_missing.stdout.strip()))
    results.append(("the missing file still raises", run_missing.returncode != 0, f"exit {run_missing.returncode}"))

    report(results)
    return 0 if all(ok for _, ok, _ in results) else 1


if __name__ == "__main__":
    sys.exit(main())

Against the starter, the checker scores zero and exits with status 1.

TEXT
$ python3 check_totals.py
FAIL  the script finishes on a file with one blank field  <- ValueError: invalid literal for int() with base 10: ''

0 of 1 checks passed

The narrow fix

Wrap only the conversion in try. When int raises, Python jumps to the matching except and skips the rest of the try block. A skipped row adds one to a counter and prints its date, and the loop moves on to the next row.

The !r in the f-string prints the repr of the value, so the empty string shows up as '' instead of vanishing. The finally at the bottom prints the summary line.

PYTHON
# totals.py
import csv
import sys

path = sys.argv[1]

total = 0
read = 0
skipped = 0
try:
    with open(path, newline="") as handle:
        for row in csv.DictReader(handle):
            read += 1
            try:
                total += int(row["minutes"])
            except ValueError:
                skipped += 1
                print(f"skipped {row['date']}: {row['minutes']!r}")
finally:
    print(f"read {read} rows, skipped {skipped}, total {total}")

The run now finishes with exit status 0. All three rows count as read, the blank one is skipped, and the total is 50.

TEXT
$ python3 totals.py sessions.csv
skipped 2026-11-04: ''
read 3 rows, skipped 1, total 50

Any other error still reaches you, because except ValueError catches ValueError and its subclasses only.

Why finally

Point the fixed script at a file that does not exist.

TEXT
$ python3 totals.py no_such_file.csv 2>&1 | sed -n '1p;$p'
read 0 rows, skipped 0, total 0
FileNotFoundError: [Errno 2] No such file or directory: 'no_such_file.csv'

The summary line prints, and the error is still there at the end. A finally block runs whether the block succeeded, raised, or returned. Unlike except, it does not catch the exception; it runs its cleanup and lets the error propagate.

The checker covers both runs, the blank field and the missing file, and all six checks pass with exit status 0.

TEXT
$ python3 check_totals.py
PASS  the script finishes on a file with one blank field
PASS  it prints the total of the rows it could read
PASS  it says which row it skipped
PASS  it prints one line per skipped row
PASS  it still reports the summary when the file is missing
PASS  the missing file still raises

6 of 6 checks passed

The trap

A bare except: is except BaseException:, so it catches more than errors. A file that calls sys.exit(3) inside try with a bare except: prints swallowed and exits 0. A file that raises KeyboardInterrupt inside try with a bare except: prints bare except swallowed it and exits 0. A deliberate exit and a Ctrl-C both turn into a successful run.

Now break your own copy. Delete the finally: line from totals.py and unindent the summary print. The checker reports 5 of 6 checks passed and exits with status 1, because the missing-file run then prints no summary at all.

Get better at shipping code.

Join the other developers getting tech updates, tips, and relaxed tutorials in their inbox every week.

Stay in the loop

Tech updates, coding tips, and relaxed insights straight to your inbox every week.

No spam. Unsubscribe anytime.

Read next

See all
PythonPython File I/O: Why the Second Read Came Back Empty

A notes script saves a line, prints it back, then counts zero. The file on disk is correct: read() left the pointer at the end, so the second call returned an empty string. Read once into a variable, or seek(0), and the count matches the file.

For developers who learn by struggling

© 2026 Inva.dev.