import codecs
import csv


def count_rows_in_delimited_file(filename, has_header=True, safe=True, delimiter=","):
    """
    Simple and efficient utility function to provide the rows in a valid delimited file
    If a header is not present, set head_header parameter to False

    Added "safe" mode which will handle any NUL BYTE characters in delimited files
    It does increase the function runtime by approx 10%.
        Example:
            "non-safe" counting ~1 million records in a delimited file takes 9s
            using "safe mode", it now takes 10s

    """
    with codecs.open(filename, "r") as f:
        if safe:
            row_count = sum(1 for row in csv.reader((line.replace("\0", "") for line in f), delimiter=delimiter))
        else:
            row_count = sum(1 for row in csv.reader(f, delimiter=delimiter))
    if has_header and row_count > 0:
        row_count -= 1

    return row_count