【python】统计代码行数 | 统计当前文件夹里所有代码文件的行数

背景

写了一堆.cs文件
想看看一共写了多少行

代码

import os
import chardet

# Check if a file has the given extension
def has_extension(file, extension):
    return os.path.splitext(file)[1] == extension

# Count the number of non-empty lines in a file
def count_lines_of_code(file):
    with open(file, 'rb') as f:
        result = chardet.detect(f.read())
        encoding = result['encoding']
    with open(file, 'r', encoding=encoding) as f:
        lines = [line.strip() for line in f if line.strip()]
        return len(lines)

# Get all files with the given extension in the current directory
def get_files_with_extension(extension):
    files = [file for file in os.listdir('.') if os.path.isfile(file) and has_extension(file, extension)]
    return files

if __name__ == '__main__':
    files = get_files_with_extension('.cs')
    total_lines = 0
    for file in files:
        lines = count_lines_of_code(file)
        print(f'{
      
      file}: {
      
      lines} lines')
        total_lines += lines
    print(f'Total lines of code in .cs files: {
      
      total_lines}')

运行结果

在这里插入图片描述

好用的话请点个赞吧QWQ

猜你喜欢

转载自blog.csdn.net/gongfpp/article/details/130294327