2014-11-24 74 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