Python appending from previous for loop iteration
<p>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.</p>

<pre><code>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&lt;wv[i]&lt;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 &lt; 0:
                peak_wv = (wv[i+2]+wv[i+1]+wv[i])/3.0
                peak_flux = flux[i+1]
                print peak_wv, peak_flux
</code></pre>

<p>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:</p>

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

<hr>

<p>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:</p>

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

<p>Could be this:</p>

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

<p>And this:</p>

<pre><code>for i in range(len(wv)):
    if 6555.0&lt;wv[i]&lt;6569.0:
</code></pre>

<p>Could be:</p>

<pre><code>for i, cur_wv in enumerate(wv):
    if 6555.0 &lt; cur_wv &lt; 6569.0:
</code></pre>

python