Content of csv file to printed in tabular form

Viewed 57

I want the content of csv file to printed in tabular form.

with open ("trial.csv","r") as f1:
csv_r=csv.reader(f1)
for i in csv_r:
    print("\t\t".join(i))

But whenever I try to run this code the content gets shuffled like if I have

name  class  section
a      xi     A

instead of this it becomes

name  class    section
a      xi   A

the "A" is not in proper column

1 Answers

To ensure each of your columns has the correct width, you would need to first read all of your data in before printing. You can then determine the maximum width of each column and then print it. For example:

import csv

def print_cols(data):
    col_spacer = "  "       # added between columns
    widths = [max(len(str(item)) for item in row) for row in zip(*data)]
    print('\n'.join(col_spacer.join(f"{col:{widths[index]}}" for index, col in enumerate(row)) for row in data))

with open("trial.csv") as f1:
    csv_r = csv.reader(f1)
    data = list(csv_r)

print_cols(data)

Giving you:

name  class  section
a     xi     A

widths is a list holding the maximum width needed for each columns. The f string here is gives each value the correct width padding. It then adds a col_spacer between each column.

Related