Search code examples
pythonrowload-csv

What is not a row in a csv file?


I came upon this code in a tutorial:

 for row in csv_reader:
        if not row:
            continue
        dataset.append(row)

Which I take to mean that if the code encounters something other than a row, just skip and continue. Is that correct?

What defines 'not row'?


Solution

  • This allows you to skip over empty lines in a CSV file.


    not row just means "row is falsey".

    In Python, the following things are falsey:

    • False
    • None
    • Numeric zeroes
    • Empty containers

    (Of course you can write your own class with a __bool__ method that does anything you want—but by convention, it should follow the same rule.)

    This is all explained in Boolean operations in the docs.

    --

    The rows iterated by a csv.reader are lists. (And lists are containers, so they're falsey iff they're empty.)

    An empty line produces an empty list; a line with text but no delimiters produces a list of one string; a line with delimiters produces a list of two or more strings.

    This is covered in the csv module docs… but not really all in one place.