从csv到表格式文件

时间:2016-11-10 12:30:19

标签: python csv

我有以下形式的.csv:

SYSID,DATA,PERIOD_NAME,ORA,MIPS 
PROD,2016-11-02,PRIME,10,3459.48 
PROD,2016-11-02,PRIME,11,2837.16 
PROD,2016-11-02,PRIME,12,2624.15

我希望在输出中获得类似这样的内容

SYSID    DATA          PERIOD_NAME  ORA    MIPS
PROD     2016-11-02    PRIME        10     3459.48
PROD     2016-11-02    PRIME        11     2837.16
PROD     2016-11-02    PRIME        12     2624.15

我试过了

import csv
inf = open('pathtofile\\out.csv')
reader=csv.reader(inf)
ofile  = open('pathtofile\\fuffa.txt', "wb")
writer = csv.writer(ofile, delimiter='\t')
for row in reader:
    writer.writerow(row)

但是给了我以下“未格式化的表格”

SYSID   DATA    PERIOD_NAME ORA MIPS
PROD    2016-11-02  PRIME   10  3459.48
PROD    2016-11-02  PRIME   11  2837.16
PROD    2016-11-02  PRIME   12  2624.15

我环顾四周,但找不到对我的问题有用的东西。 任何暗示都非常受欢迎。

1 个答案:

答案 0 :(得分:4)

您可以按如下方式滚动自己的列格式化程序:

import csv

def write_cols(data):
    col_spacer = "   "      # added between columns
    widths = [0] * len(data[0])

    for row in data:
        widths[:] = [max(widths[index], len(str(col))) for index, col in enumerate(row)]

    return [col_spacer.join("{:<{width}}".format(col, width=widths[index]) for index, col in enumerate(row)) for row in data]


with open('input.csv', 'rb') as f_input, open('output.txt', 'w') as f_output:
    rows = list(csv.reader(f_input))

    for row in write_cols(rows):
        f_output.write(row + '\n')

给你以下输出文件:

SYSID   DATA         PERIOD_NAME   ORA   MIPS    
PROD    2016-11-02   PRIME         10    3459.48 
PROD    2016-11-02   PRIME         11    2837.16 
PROD    2016-11-02   PRIME         12    2624.15

这计算每列中所有值的最大宽度,然后相应地对齐条目。请注意,请确保CSV文件中的所有条目包含相同数量的列,例如没有空行。

为了在Python 2.6中工作,可以按如下方式修改脚本:

import csv

def write_cols(data):
    col_spacer = "   "      # added between columns
    widths = [0] * len(data[0])

    for row in data:
        widths[:] = [max(widths[index], len(str(col))) for index, col in enumerate(row)]

    return [col_spacer.join("{0:<{width}}".format(col, width=widths[index]) for index, col in enumerate(row)) for row in data]


with open('input.csv', 'rb') as f_input:
    with open('output.txt', 'w') as f_output:
        rows = list(csv.reader(f_input))

        for row in write_cols(rows):
            f_output.write(row + '\n')