[Tutor] Printing columns of data
Kent Johnson
kent37 at tds.net
Tue Feb 8 21:49:21 CET 2005
Kooser, Ara S wrote:
> Hello all,
>
> I am writing a program to take a data file, divide it up into columns
> and print the information back with headers. The data files looks like this
>
> 0.0 -3093.44908 -3084.59762 387.64329 26.38518 0.3902434E+00
> -0.6024320E-04 0.4529416E-05
> 1.0 -3094.09209 -3084.52987 391.42288 105.55994 0.3889897E+00
> -0.2290866E-03 0.4187074E-03
> 2.0 -3094.59358 -3084.88826 373.64911 173.44885 0.3862430E+00
> -0.4953443E-03 0.2383621E-02
> etc…
> 10.0 ...
>
> So I wrote the program included below and it only prints the last line
> of the file.
>
> Timestep PE
> 10.0 -3091.80609
>
> I have one question. Do I need to put ts and pe into a list before I
> print then to screen or I am just missing something. Thanks.
You should print the header before the loop, and the contents inside the loop. So:
print """
Timestep PE"""
for line in cols:
ts = line[0]
# print line[0]
pe = line[1]
# print line[1]
# The next line is indented so it is included in the loop:
print "%s %s " % (ts,pe)
You probably will want to set the field width in the print format so the columns all line up,
something like this (just guessing on the widths):
print "%10s %10" % (ts,pe)
You might be interested in this recipe which does a very slick job of pretty-printing a table:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/267662
Kent
>
> Ara
>
> import string
>
> inp = open("fort.44","r")
> all_file = inp.readlines()
> inp.close()
>
> outp = open("out.txt","w")
>
> cols = map(string.split,all_file)
> ##print cols
>
> Data = {}
> for line in cols:
> ts = line[0]
> # print line[0]
> pe = line[1]
> # print line[1]
>
> print """
>
> Timestep PE"""
> print "%s %s " % (ts,pe)
>
>
> outp.close()
>
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list