Search code examples
pythoncsv

How to check whether csv.DictReader object is empty or not


I am writing python code to read contents from a csv file with the DictReader.

with open(parafile, "rb") as paracsv:         
    #Read in parameter values as a dictionary
    paradict = csv.DictReader(paracsv)
    if paradict.line_num <= 1:
        return None

I want to be able to return immediately if there is no more than one row read from the csv file.

I have tried checking the line_num, but it always returns 0 even there are more than one row in the file. Does anyone know what is the correct/efficient way to check this?

Thanks


Solution

  • You cannot, without reading lines, know how many there are in the file. Note that the csvreader.line_num attribute reflects the number of lines read so far, not the number of lines present in the file:

    The number of lines read from the source iterator. This is not the same as the number of records returned, as records can span multiple lines.

    Just read your file; if there is only one row in the file, you'll end up returning early anyway.

    If you only return None if there were no rows read, you could use:

    with open(parafile, "rb") as paracsv:         
        #Read in parameter values as a dictionary
        paradict = csv.DictReader(paracsv)
        has_rows = False
        for line in paradict:
            has_rows = True
    
        if not has_rows:
            return None
    

    If there are no rows beyond the first header row in the file, this returns early, as the for loop immediately terminates.