使用Python将列名称与CSV文件中的数据对齐

gee*_*hic 3 python csv

这是我用来将数据写入.csv文件的代码.

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)
Run Code Online (Sandbox Code Playgroud)

输出看起来像这样:

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
Run Code Online (Sandbox Code Playgroud)

如何对齐它以使每列下的数据以更易于阅读的方式完美对齐?期望的输出:(即使数据位于列的中心也没问题)

  faceXpos  faceYpos    faceHeight  faceWidth   imageViewHeight imageViewWidth  tshirtXpos  tshirtYpos  tshirtWidth tshirtHeight
  118       432         84          84          568             320             13.0        136         294.0       346.0
Run Code Online (Sandbox Code Playgroud)

E.Z*_*.Z. 5

首先,你想要的是一个"固定宽度文件",而不是一个CSV.

有一个叫做的模块prettytable可以帮助你:

from prettytable import PrettyTable

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

t.align='l'
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)
Run Code Online (Sandbox Code Playgroud)

输出:

 A            B    C
 111          222  333
 444          555  666
 longer text  777  even longer text here
Run Code Online (Sandbox Code Playgroud)