Alessandro Blasetti - 10 months ago 55

Python Question

I have a .csv in the following form:

`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

and I would like to obtain in output something like this

`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

I have tried

`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)

but gives me the following "unformatted table"

`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

I have looked around but I can not find something useful for my problem.

Any hint is very much appreciated.

Answer Source

You could roll your own column formatter as follows:

```
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')
```

Giving you the following output file:

```
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
```

This calculates the largest width for all values in each column and then spaces entries accordingly.