2014-11-24 100 views

回答

2

如果您不需要使用Python脚本,可以做到这一点在* NIX命令行:

wc -l *.csv > outputfilename 

如果你真的想使用Python这样做:

import os 
import csv 

dirname = 'directory/with/csv/files' 
outfile = open('path/to/output/file') 
for fname in os.listdir(dirname): 
    if not fname.endswith('.csv'): 
     continue 
    with open(os.path.join(dirname, fname)) as infile: 
     numlines = sum(1 for row in csv.reader(infile)) 
     outfile.write("file {} contains {} lines\n".format(fname, numlines)) 
outfile.close() 
+0

,感谢您的快速帮助... – ak548 2014-11-25 00:43:41

0

这方法计数行大约比具有一百万行文件的sum(generator-expression)快5倍。它只计算所有换行符。

with open(csv_file) as f: 
    s = f.read() 
numlines = s.count('\n') 

您可能想要替换为@ inspectorG4dget的解决方案,看看它是否有所作为。

+0

,感谢您的帮助 – ak548 2014-11-25 00:45:50

+0

@ ak548请参阅编辑。 – wwii 2014-11-25 04:32:32