import csv


def split_csv_size(csv_file, size, folder, keepheader=True):
    """[Split a large csv file into small csv files with certain rows in each small csv file]
    
    Arguments:
        csv_file {[Path]} -- [the Path object for the large csv file to split]
        size {[int]} -- [number of observations in each small csv file]
        folder {[Path]} -- [the folder to save all the small csv files]
    
    Keyword Arguments:
        keepheader {bool} -- [whether to keep the header row in the small csv files] 
        (default: {True})
    
    Returns:
        [list] -- [list of Path for all the small csv files generated]
    """
    csv_name = csv_file.name[:-4]
    with open(csv_file, newline='') as f:
        reader = csv.reader(f)
        header = next(reader)
        current_piece = 1
        current_out = folder / f'{csv_name}_{current_piece}.csv'
        current_out_writer = csv.writer(open(current_out, 'w', newline=''))
        if keepheader == True:
            current_out_writer.writerow(header)
        current_limit = size
        for i, row in enumerate(reader):
            if i + 1 > current_limit:
                current_piece += 1
                current_limit = size * current_piece
                current_out = folder / f'{csv_name}_{current_piece}.csv'
                current_out_writer = csv.writer(open(current_out, 'w', newline=''))
                if keepheader == True:
                    current_out_writer.writerow(header)
            current_out_writer.writerow(row)
        outfile = [f'{csv_name}_{i}.csv' for i in range(1,current_piece+1)]
    return sorted([folder / outfile[i] for i in range(current_piece)])