【问题标题】:count lines in multiple files and output along with file names计算多个文件中的行数并连同文件名一起输出
【发布时间】: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

标签: python count


【解决方案1】:

你真的很亲密!只需打开一次计数文件,而不是在循环内:

import glob
with open('countfile' , 'w') as out:
    list_of_files = glob.glob('./*.linear')
    for file_name in list_of_files:
        with open(file_name, 'r') as f:
            count = sum(1 for line in f)
            out.write('{c} {f}\n'.format(c = count, f = file_name))

每次以w 模式打开文件时(例如open('countfile', 'w')),countfile 的内容(如果已存在)都会被删除。这就是为什么你只需要调用一次。

【讨论】:

  • 感谢替换 print >> ... 的东西。我从不喜欢print 的那种形式。它似乎不适合 python 的其余语法。
  • @mgilson:是的,我从不使用print out >>。而print 是 Python3 中的一个函数,所以现在使用它没有什么意义。 :)
  • file.write略有不同。它在传递给它的项目上隐式调用str,并自动附加一个换行符(当然,除非你有一个尾随逗号)。也就是说,我还是宁愿使用字符串格式化或插值。
最近更新 更多