import csv


def write_csv(path, rows, header=None, delimiter=',', dialect='excel'):
    """
    wrapper to write csv module that normalises the length of rows
    :param path: writes the csv to the given path
    :param rows: list of iterables corresponding to rows
    :param header: optional first row to include
    :param delimiter: optional.
    :param dialect: optional dialect that csv will use
    :return: writes a file
    """
    def normalise(rows):
        """
        calculates the longest line and adds the necessary empty strings so that all rows have the same length
        :param rows: list of iterables
        :return: a list of rows where each row is a list.
        """
        # calculate longest
        longest_row = 0
        for r in rows:
            if len(r) > longest_row:
                longest_row = len(r)
        # normalise rows
        norm_rows = []
        for r in rows:
            if len(r) < longest_row:
                norm_rows.append([a for a in r]+['' for i in range(longest_row-len(r))])
            else:
                norm_rows.append(r)
        return norm_rows

    with open(path, 'w', encoding='utf-8-sig') as csvfile:
        file_writer = csv.writer(csvfile, dialect=dialect, delimiter=delimiter)
        if header:
            rows = [header]+rows
            rows = normalise(rows)
            for row in rows:
                file_writer.writerow(row)
        else:
            rows = normalise(rows)
            for row in rows:
                file_writer.writerow(row)