Skip to content

Instantly share code, notes, and snippets.

@tony-landis
Created December 5, 2008 18:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save tony-landis/32423 to your computer and use it in GitHub Desktop.
Save tony-landis/32423 to your computer and use it in GitHub Desktop.
Convert CSV string to fixed width text table
"""
Convert CSV string to fixed width text table. Supports multi-line rows, column width limits, and creates a header row automatically
@author Tony Landis
@link http://www.tonylandis.com
@license GPL
"""
from math import ceil
class CsvToTxt():
rows=[]; cs=[]; rs=[]; keys=[];
mH = 3; mW = 20
pcen = "+"; prow = "-"; pcol = "|"; pcolm = ":"
nline = False
def __init__(self, data):
x = 0
for row in data.split("\n")[:]:
self.rs.append(x)
self.rs[x]=1
cols = row.split(",")
self.rows.append(cols)
if(x==0):
self.keys = cols
for index in range(len(cols)):
self.cs.append(index);
for index, item in enumerate(cols): self.setMax(x, index, item)
x += 1;
def setMax(self, x, y, data):
h = 1
w = len(data)
if w > self.mW:
h = ceil(w % self.mH); w = self.mW
if self.cs[y] < w: self.cs[y] = w
if self.rs[x] < h: self.rs[x] = h
def printLine(self,nl=True):
if self.nline: return self.nline
else: self.nline = self.pcen
for len in self.cs[:]:
self.nline += self.prow.rjust(len, self.prow) + self.prow + self.prow + self.pcen;
return self.nline;
def printRow(self, rowKey):
string = ''
line=0
while line < self.rs[rowKey]:
start = self.mW * (line)
if line>0:
pcol = self.pcolm
end = self.mW+start
else:
pcol = self.pcol
end = self.mW
string = pcol
for index, item in enumerate(self.rows[rowKey]):
string += " "
string += item[start:end].ljust(self.cs[index], ' ')
string += " " + pcol
print string
line += 1
return string
def render(self):
for i in range(len(self.rows)):
if i == 0: print self.printLine()
self.printRow(i)
if i == 0: print self.printLine()
print self.printLine()
if __name__ == "__main__":
string = ''
i=0
while i < 100:
i += 1
string += "\nPython,CSV,=> Text\n100,200,300\nJack and Jill went down the hill,and ? came tumbling,after?\nHello,World,null"
f = CsvToTxt("col1,col2,col3" + string)
f.render()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment