Python appending from previous for loop iteration
Question: I have a very simple but annoying problem. I am reading in a list of files one
by one whose names are stored in an ascii file ("file_input.txt") and
performing calculations on them. My issue is that when I print out the result
of the calculation ("print peak_wv, peak_flux" in the script below) it appends
the previous printout. Below is the code I have written, please help me see
what I'm doing wrong here.

    
    
    from math import*
    
    wv = []
    flux = []
    fits = []
    
    p = open("file_input.txt","r")
    for line in p:
        fits.append(str(line.split()[0]))
    p.close()
    
    for j in range(len(fits)):
        f = open("%s"%(fits[j]),"r")
        for line in f:
            wv.append(float(line.split()[0]))
            flux.append(float(line.split()[1]))
        f.close()
        print "%s"%(fits[j])
        for i in range(len(wv)):
            if 6555.0<wv[i]<6569.0:
                m1 = (flux[i+1]-flux[i])/(wv[i+1] - wv[i])
                m2 = (flux[i+2]-flux[i+1])/(wv[i+2] - wv[i+1])
                if m2*m1 < 0:
                    peak_wv = (wv[i+2]+wv[i+1]+wv[i])/3.0
                    peak_flux = flux[i+1]
                    print peak_wv, peak_flux
    


Answer: Based on your comment I believe the issue is that you are appending the data
with each new file. You probably want to clear wv and flux for each new file.
For example:

    
    
    for j in range(len(fits)):
        wv = []
        flux = []
        f = open("%s"%(fits[j]),"r")
    

* * *

Edit: I should also point out that you aren't actually using any math
functions so you don't need that import, and there are a bunch of ways to make
this code more pythonic. You can use the "with open" idiom to avoid having to
manually close the file. You can also use basic for loops and/or "enumerate"
to make your for loops cleaner. For example, this:

    
    
    for j in range(len(fits)):
        f = open("%s"%(fits[j]),"r")
        # code
        f.close()
    

Could be this:

    
    
    for file in fits:
        with open(file, "r") as f:
            # code
    

And this:

    
    
    for i in range(len(wv)):
        if 6555.0<wv[i]<6569.0:
    

Could be:

    
    
    for i, cur_wv in enumerate(wv):
        if 6555.0 < cur_wv < 6569.0:
    

