import os.path
import time #SUPPRIMER

def _init(path_to_file, fields):
    """Init csv file with fields"""
    with open(path_to_file, "a") as csv_file:
        num_fields = len(fields)
        assert num_fields > 0, "0 fields to write in csv"
        header = ("{},"*(num_fields-1)+"{}\n").format(*fields)
        csv_file.write(header)


def csv_write(path_to_file, logs_dict, fields=None):
    """Write to file"""
    if not os.path.isfile(path_to_file):
        if fields:
            _init(path_to_file, fields)
        else:
            fields = [key for key in logs_dict.keys()]
            _init(path_to_file, fields)

    with open(path_to_file, "a") as csv_file:
        if fields:
            logs_csv = [round(logs_dict[field], 2) for field in fields]
        else:
            logs_csv = [round(logs_dict[key], 2) for key in logs_dict.keys()]
        num_logs = len(logs_csv)
        csv_file.write(("{},"*(num_logs-1)+"{}\n").format(*logs_csv))
