Skip to content

Instantly share code, notes, and snippets.

@1328
Created May 14, 2014 21:31
Show Gist options
  • Select an option

  • Save 1328/e00e61e504bff65c8969 to your computer and use it in GitHub Desktop.

Select an option

Save 1328/e00e61e504bff65c8969 to your computer and use it in GitHub Desktop.
Pretty table
import csv
from pprint import pprint
FN = 'tmpdata.txt'
def write_csv(fn, lines = 4):
'''writes a csv with a header, total and lines lines inbetween'''
with open(fn, mode='w') as fh:
w = csv.writer(fh, delimiter=',')
w.writerow(['header'] + ['data']*3)
for _ in range(lines):
w.writerow(['line'] + ['data']*3)
w.writerow(['total'] + ['data']*3)
def read_csv(fn):
'''reads csv named fn and returns data in two dimensional list'''
data = []
with open(fn, mode='r') as fh:
reader = csv.reader(fh, delimiter=',')
for row in reader:
if row:
data.append(row) # stupid blank rows!
return data
def pretty_table(table):
'''adds in the three new headers, one short on top '''
''' and two full in line'''
table.insert(0,['','extra header 1','exh','exh'])
table.insert(2,['extra header 2','exh','exh','exh'])
table.insert(-1,['extra header 3','exh','exh','exh'])
return table
def pretty_table_dict(table):
'''adds in the same headers, but stores them in a dict'''
'''this allows for easier expansion in the future '''
'''but take care as dictionaries are not ordered!'''
'''so since you are modifying the table as you go, you need to take care'''
'''that everything is in the right order'''
a_dict = {0:['','extra header 1','exh','exh'],
2:['extra header 2','exh','exh','exh'],
-1:['extra header 3','exh','exh','exh']
}
for k,v in sorted(a_dict.items()):
# print(k) -- note this would show you that it runs in the following order:
# -1, 0, 2 --> so be careful how you structure
table.insert(k,v)
return table
def main():
write_csv(FN, lines = 9) # write a new csv file -- try changing lines = x to mess it up
table = read_csv(FN) # now load it into table
pprint(table) # let's see how it looks at the start
table = pretty_table_dict(table) # now let's make it pretty
pprint(table) # and print again
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment