I was trying to write the output of a loop on a file. The problem is the writing repeats for each loop.

prev_line = ""

while line: 

    Total = 0
       
    fields = line.split()
       
    N = len(fields)
    name = fields[0]
    
    #sum each 5 fields over the raw:
    for step in range (6, N, 5):
        Total2 = 0
        
        for i in range (step-5, step, 1):
            Total2 += float(fields[i])
    
            # do something
            
            prev_line = Total2
               
  
        print_grades(name, "%d" % (prev_line))

The output looks like this:

Big-man 215
Big-man 285
Big-man 232

but I want it to be
Big-man 215 285 232 ....

would you please help me with this?

chebude

Try something along these lines:

while line: 

    Total = 0
    fields = line.split()
    N = len(fields)
    print fields[0], # Print name. Notice trailing comma

    #sum each 5 fields over the raw:
    for step in range (6, N, 5):
        Total2 = 0        
        for i in range (step-5, step, 1):
            Total2 += float(fields[i])
    
            # do something
            
        print "%d" % Total2, # Another trailing comma
    print # NO trailing comma

Thank you! your suggestion works on the consol, the problem is writing to a file.

I am trying to pass the

print_grades(name, "%d" % (prev_line))

to a print function on file

def print_grades(name, Total2):

print >>ofh, name, Total2

doesnt put if in column

... but if you replace the plain print calls with print >>ofh, you should see the same results.

I recognize this may not be the way you want your program to work. You may need to write a print_grades() function for other reasons. In which case I suggest you define print_grades() to take a list as its second argument a la:

def print_grades(name, numbers):
    print >>ofh, name, #Print the name (note comma)
    for n in numbers:
        print >>ofh, ("%d" % n), # Print each number (note comma)
    print >>ofh # End of line

Of course now you need to recode your caller routine to build up a list instead of a single total, but the idea is you only make one call to print_grades() for each name. I think that is the right way to go here.

Thanks BearofNH. The first option without the print function works. It will do for now. I was not able to work with the print_grades() function but will keep trying to fix it!

This article has been dead for over six months. Start a new discussion instead.