简体   繁体   中英

Appending output of a for loop for Python to a csv file

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 Linecount.csv . 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.

For the csv file it is not.

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()

Please check your indentation.

You are looping through each file using for file in glob.glob("*.txt"):

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

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

I've not run but reordering as follows may solve the issue:

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM