python - From csv to table-like file -


i have .csv in 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 obtain in output 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') row in reader:     writer.writerow(row) 

but gives me 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 can not find useful problem. hint appreciated.

you roll own column formatter follows:

import csv  def write_cols(data):     col_spacer = "   "      # added between columns     widths = [0] * len(data[0])      row in data:         widths[:] = [max(widths[index], len(str(col))) index, col in enumerate(row)]      return [col_spacer.join("{:<{width}}".format(col, width=widths[index]) index, col in enumerate(row)) row in data]   open('input.csv', 'rb') f_input, open('output.txt', 'w') f_output:     rows = list(csv.reader(f_input))      row in write_cols(rows):         f_output.write(row + '\n') 

giving 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 largest width values in each column , spaces entries accordingly. note, make sure of entries in csv file contain same number of columns, example no empty lines.


for work in python 2.6, script can modified follows:

import csv  def write_cols(data):     col_spacer = "   "      # added between columns     widths = [0] * len(data[0])      row in data:         widths[:] = [max(widths[index], len(str(col))) index, col in enumerate(row)]      return [col_spacer.join("{0:<{width}}".format(col, width=widths[index]) index, col in enumerate(row)) row in data]   open('input.csv', 'rb') f_input:     open('output.txt', 'w') f_output:         rows = list(csv.reader(f_input))          row in write_cols(rows):             f_output.write(row + '\n') 

Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -