How to sort .csv file values by combining like strings using python3
Question: I'm still learning so please bear with me. I've been trying to figure this out
for sometime now but have not found what im looking for.

    
    
    My Product.csv file looks like this.
    
    111 ; Info1 ; Description 1 ; Remarks1
    123 ; Info1 ; Description 1 ; Remarks1
    156 ; Info2 ; Description 2 ; Remarks2
    124 ; Info3 ; Description 3 ; Remarks3
    
    I would like to combine entries that are similar like this.
    
    111, 123 ; Info1 ; Description 1 ; Remarks1
    156 ; Info2 ; Description 2 ; Remarks2
    124 ; Info3 ; Description 3 ; Remarks3
    
    From here i can manipulate my csv file in Excel using vba to insert into a quotation.
    

This is what i would like to achieve using Python. I'm stummped on where to
start. I think I need to sart by opening the file and then reading the csv
file. After that assign variable to #(i.e. 111) , info, Description, Remarks.
Then sort thru the variables and combine like #'s. Then write it back to the
file. Please let me know if you need me to calrify anything.


Answer: That's a task for
[itertools.groupby](https://docs.python.org/3.4/library/itertools.html#itertools.groupby)

**EDIT:** I re-factored the first version to improve readability

    
    
    # file group_by_trailing_py2.py
    import os
    import csv
    from itertools import groupby
    
    DELIM=';'
    IN_FILENAME = 'My Product.csv'
    OUT_FILENAME = 'My Product.grouped.csv'
    
    ############  skip this if you run  it against productive data ###############
    DATA = '''111 ; Info1 ; Description 1 ; Remarks1
    123 ; Info1 ; Description 1 ; Remarks1
    156 ; Info2 ; Description 2 ; Remarks2
    124 ; Info3 ; Description 3 ; Remarks3'''
    
    if (os.environ.get('WITH_DATA_GENERATION')):
        open(IN_FILENAME,'w').write(DATA)
    ##############################################################################
    
    keyfunc = lambda row: row[1:]
    
    with open(IN_FILENAME) as csv_file:
        rows = sorted(csv.reader(csv_file, delimiter=DELIM), key=keyfunc)
    
    it = map(lambda t: [", ".join(v[0].strip() for v in t[1]) + " "] + t[0],
                groupby(rows, key=keyfunc))
    
    with open(OUT_FILENAME, 'w') as csv_file:
        writer = csv.writer(csv_file, delimiter=DELIM)  
        for row in it:
            writer.writerow(row)
    

if run with

    
    
    WITH_DATA_GENERATION=1 python3 group_by_trailing_pk2.py
    

it produces `My Product.grouped.csv` with the content:

    
    
    111, 123 ; Info1 ; Description 1 ; Remarks1
    156 ; Info2 ; Description 2 ; Remarks2
    124 ; Info3 ; Description 3 ; Remarks3
    

Because you have an existing workload **you will not set
WITH_DATA_GENERATION** and delete the code between and including the
`'####...'` comment lines.

