计算多个文件中的行并输出文件名

jul*_*les 1 python count

我想获取文件夹中每个文件中的行数,然后相邻地打印出行数和文件名.刚刚进入编程世界,我设法编写了这个简短的代码,从这里和那里借用它们.

#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
Run Code Online (Sandbox Code Playgroud)

但是这只给出了一个文件的输出.

这可以很容易地wc -l *在shell中使用.linear,但我想知道如何在python中执行此操作.

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

unu*_*tbu 5

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

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))
Run Code Online (Sandbox Code Playgroud)

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