我想要获取文件夹中每个文件的行数,并打印出与文件名相邻的行数。刚进入编程世界时,我设法编写了这个简短的代码,并从各处借用它们。在多个文件中输入多行文件并输出文件名
#count the number of lines in all files and output both count number and file name
import glob
list_of_files = glob.glob('./*.linear')
for file_name in list_of_files:
with open (file_name) as f, open ('countfile' , 'w') as out :
count = sum (1 for line in f)
print >> out, count, f.name
但是,这给出了只有一个文件的输出。
这可以很容易地使用wc -l *
.linear在shell中完成,但我想知道如何在python中做到这一点。
P.S:我真心希望我不会重复提问!
这是因为您每次迭代都会一次又一次地截断countfile。 –