3

我想获取文件夹中每个文件的行数,并将行数与文件名相邻打印出来。刚刚进入编程世界,我设法编写了这段简短的代码,到处借用它们。

#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 *在 shell 中使用 .linear 来完成,但我想知道如何在 python 中做到这一点。

PS:我真诚地希望我不是重复问题!

4

1 回答 1

7

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

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(如果已存在)的内容将被删除。这就是为什么你只需要调用一次。

于 2012-12-20T13:47:09.600 回答