[Tutor] Print a list in columnar format
Douglas N. Shawhan
lysdexia at crackrabbit.com
Thu Oct 7 05:46:12 CEST 2004
Whoops, but I didn't really properly answer your question of how to get
a _list_ to print in pretty columns!
Okay, I have a file called csv.csv that has 100 rows, 10 columns wide
with entries no greater than 3 characters long.
f=open('csv.csv', 'r')
l=f.readlines()
for line in l:
line=line.split(',')
row = (line[0],line[1],line[2],line[3],line[4],\
line[5],line[6],line[7],line[8],line[9])
print '%5s %5s %5s %5s %5s %5s %5s %5s %5s %5s'%(row)
Which gives me (shortened):
132 207 943 497 892 47 436 374 746 33
511 894 99 391 743 39 782 887 364 744
214 490 486 57 326 221 726 388 997 997
271 938 556 959 53 585 798 906 501 53
893 84 900 920 897 180 34 867 575 210
5 104 717 411 839 115 921 213 240 874
636 748 717 830 114 759 819 342 470 153
667 758 37 473 236 998 313 451 350 972
749 769 689 106 589 906 387 470 677 90
461 795 129 257 383 937 663 537 516 796
601 951 295 996 832 984 423 686 79 313
247 421 728 866 570 721 627 374 929 880
95 518 561 362 11 751 945 99 341 561
647 226 505 188 433 83 315 101 809 346
282 30 230 986 398 668 852 895 304 930
344 473 153 47 329 291 404 332 521 383
677 273 950 943 948 172 399 83 421 496
for output. *Whew* sorry if the previous post was confusing.
To summarize:
#open our file
f=open('csv.csv', 'r')
#read in each line as a list member
l=f.readlines()
for line in l:
#split each line into a list of comma seperated values
line=line.split(',')
#then put the values into a tuple (less confusing, hopefully)
row = (line[0],line[1],line[2],line[3],line[4],\
line[5],line[6],line[7],line[8],line[9])
#and specify a five space offset for each value when it is printed!
print '%5s %5s %5s %5s %5s %5s %5s %5s %5s %5s'%(row)
Hope this helps.
(And here I thought you Forest Service folk spent all your time having
fun in the woods. I hope you are doing all this coding on a laptop in a
fire tower! :-)
More information about the Tutor
mailing list