Appending output of a for loop for Python to a csv file
<p>I have a folder with .txt files in it. My code will find the line count and character count in each of these files and save the output for each file in a single csv file in a different directory. The csv file is <em>Linecount.csv</em>. For some reason the output to csv file is repeating for character and linecount for the last output, though printing the output is producing correct results. The output of the  print statement is correct.</p>

<p>For the csv file it is not.</p>

<pre><code>import glob 
import os 
import csv 

os.chdir('c:/Users/dasa17/Desktop/sample/Upload') 

for file in glob.glob("*.txt"): 
    chars = lines = 0 
    with open(file,'r')as f: 
        for line in f: 
        lines+=1 
        chars += len(line) 
    a=file 
    b=lines 
    c=chars 
    print(a,b,c) 

    d=open('c:/Users/dasa17/Desktop/sample/Output/LineCount.csââv', 'w') 
    writer = csv.writer(d,lineterminator='\n') 
    for a in os.listdir('c:/Users/dasa17/Desktop/sample/Upload'): 
        writer.writerow((a,b,c)) d.close()
</code></pre>

<p>Please check your indentation.</p>

<p>You are looping through each file using <code>for file in glob.glob("*.txt"):</code> </p>

<p>This stores the last result in <code>a</code>,<code>b</code>, and <code>c</code>.  It doesn't appear to write it anywhere.</p>

<p>You then loop through each item using <code>for a in os.listdir('c:/Users/dasa17/Desktop/sample/Upload'):</code>, and store <code>a</code> from this loop (the filename), and the last value of <code>b</code> and <code>c</code> from the initial loop.</p>

<p>I've not run but reordering as follows may solve the issue:</p>

<pre><code>import glob 
import os 
import csv 

os.chdir('c:/Users/dasa17/Desktop/sample/Upload') 
d=open('c:/Users/dasa17/Desktop/sample/Output/LineCount.csââv', 'w')
writer = csv.writer(d,lineterminator='\n') 

for file in glob.glob("*.txt"): 
        chars = lines = 0 
        with open(file,'r') as f: 
                for line in f: 
                lines+=1 
                chars += len(line) 
        a=file 
        b=lines 
        c=chars 
        print(a,b,c) 
        writer.writerow((a,b,c))
d.close()
</code></pre>

python csv