简体   繁体   English

将Python的for循环的输出附加到csv文件

[英]Appending output of a for loop for Python to a csv file

I have a folder with .txt files in it. 我有一个带有.txt文件的文件夹。 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. 我的代码将在每个文件中找到行数和字符数,并将每个文件的输出保存在不同目录中的单个csv文件中。 The csv file is Linecount.csv . csv文件是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. 由于某些原因,尽管打印输出会产生正确的结果,但对csv文件的输出会重复最后一个输出的字符和行数。 The output of the print statement is correct. 打印语句的输出正确。

For the csv file it is not. 对于csv文件则不是。

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"): 您正在for file in glob.glob("*.txt"):使用for file in glob.glob("*.txt"):遍历每个文件for file in glob.glob("*.txt"):

This stores the last result in a , b , and c . 这会将最后的结果存储在abc 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. 然后,通过每个项目循环使用for a in os.listdir('c:/Users/dasa17/Desktop/sample/Upload'):和存储a从这个循环(的文件名),以及最后的值bc从初始循环开始。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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