【发布时间】:2025-12-07 01:40:01
【问题描述】:
我想获取文件夹中每个文件的行数,然后将行数与文件名相邻打印出来。刚刚进入编程世界,我设法编写了这段简短的代码,到处借用它们。
#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
但这只会输出其中一个文件。
这可以很容易地在 shell 中使用 wc -l *.linear 完成,但我想知道如何在 python 中做到这一点。
P.S : 我真诚地希望我没有重复问题!
【问题讨论】:
-
那是因为您每次迭代都会一次又一次地截断
countfile。