Align column names with data in a CSV file using Python

Issue

This is the code I am using to write data to a .csv file.

with open('temp.csv', 'a') as fp:
        a = csv.writer(fp, delimiter='\t')
        data = [['faceXpos','faceYpos','faceHeight','faceWidth','imageViewHeight','imageViewWidth','tshirtXpos', 'tshirtYpos','tshirtWidth','tshirtHeight'],
                [faceXpos, faceYpos, faceHeight, faceWidth, imageViewHeight, imageViewWidth, tshirtXpos, tshirtYpos, tshirtWidth, tshirtHeight]]
        a.writerows(data)

The output looks like so:

faceXpos    faceYpos    faceHeight  faceWidth   imageViewHeight imageViewWidth  tshirtXpos  tshirtYpos  tshirtWidth tshirtHeight
118 432 84  84  568 320 13.0    136 294.0   346.0
faceXpos    faceYpos    faceHeight  faceWidth   imageViewHeight imageViewWidth  tshirtXpos  tshirtYpos  tshirtWidth tshirtHeight
117.4   433.81  82.35999    82.36   568 320 14.45   134.19  288.26  340.09

How do I align it so that the data under each column is perfectly aligned in a way that is easier to read? Desired output: (even having the data at the center of a column would be fine)

  faceXpos  faceYpos    faceHeight  faceWidth   imageViewHeight imageViewWidth  tshirtXpos  tshirtYpos  tshirtWidth tshirtHeight
  118       432         84          84          568             320             13.0        136         294.0       346.0

Solution

First of all what you want is a "fixed-width file", and not a CSV.

There is a module called prettytable that could help you with that:

from prettytable import PrettyTable

# Initialize the object passing the table headers
t = PrettyTable(['A', 'B', 'C'])

t.align='l'  # align left 
t.border=False

t.add_row([111,222,333])
t.add_row([444,555,666])
t.add_row(['longer text',777,'even longer text here'])

print str(t)

Output:

 A            B    C
 111          222  333
 444          555  666
 longer text  777  even longer text here

p.s. In case you need sorting, use t.sortby as detail here

Answered By – E.Z.

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published