Find the bug · #11 · Empty and null Hard Python
An empty file has “1 record”
The import screen counts records in a CSV file, and empty files and blank lines throw the count off.
On this page
The report
Before importing a CSV file, the app says how many records it has, one per line. An empty file shows “1 record”, and files with blank lines show too many.
The code
Read it first: what should it do? Then click the line where you think the bug is.
def count_records(text):
"""How many non-empty records are in a CSV export, one per line."""
lines = text.strip().split("\n")
return len(lines)Read it, then pick a line.
Try it in a Python shell: what does "".split("\n") return?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
print(count_records("1,Asha\n2,Ravi"))
print(count_records(""))
print(count_records("1,Asha\n\n2,Ravi\n"))It prints
2 1 3
It should print
2 0 2
Show the answer: the bug, the fix, and how you’d find it
The bug (line 3)
Line 3 splits the text on newlines and counts the pieces. But splitting an empty string gives [""]: a list with one empty piece. Blank lines in the middle become empty pieces too. Both get counted as records. Count only the lines that have something in them.
The fix
1def count_records(text):2 """How many non-empty records are in a CSV export, one per line."""3 lines = text.strip().split("\n")3 lines = [line for line in text.splitlines() if line.strip()]4 return len(lines)How you’d find it
- Reproduce with the smallest bad input, an empty file: 1 instead of 0.
- Print
linesfor that input:[""]. The split never returns an empty list. - Try a blank line in the middle: it shows up as another
"". So the fix is to drop empty lines, not to subtract one.
The test that catches it
It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.
assert count_records("") == 0
assert count_records("1,Asha\n\n2,Ravi\n") == 2
assert count_records("1,Asha") == 1Where else this bites
- JavaScript:
"".split(",")is[""], with length 1. - Counting words with
split(" ")when there are double spaces.