Home » Python » List of columns with different length to csv in python-Exceptionshub

List of columns with different length to csv in python-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I have a large list (more than 100 values) of column values with this tructure:

columns = [['h1','v11'],['h2','v21','v22','v23'], ['h3','v31'], ['h4', 'v41','v42']]

I would like to save it as a csv:

h1,h2,h3,h4
v11,v21,v31,v41
,v22,,v42
,v23,,

Because this question was closed earlier than anyone could answer it here is my solution:

import csv    

def col_to_rows(columns):
    col_count = len(columns)
    rows_count = max([len(i) for i in columns])
    rows = [[] for x in range(rows_count)]
    for i in range(rows_count):
        for j in range(col_count):
            try:
                rows[i].append(columns[j][i])
            except:
                rows[i].append(None)
    return rows

columns = [['h1','v11'],['h2','v21','v22','v23'], ['h3','v31'], ['h4', 'v41','v42']]
rows = col_to_rows(columns)    
with open('file.csv', 'w', newline='', encoding='utf-8') as f:
    writer = csv.writer(f)
    writer.writerows(rows)
How to&Answers: