给出工程路径、指定代码类型,计算总共有多少行代码。
以下代码的原理是,递归搜索文件夹下的源码文件,然后统计该文件有多少行,然后累加。
# -*- coding: utf-8 -*- # @Author : ZhaoKe # @Time : 2021-10-08 18:08 import os sum_line_count = 0 def count_file_line(path): # print("当前文件:", path) count = 1 with open(path, 'r', encoding="utf_8_sig") as f: line = f.readline() while line: line = f.readline() count += 1 return count def count_dir_files_code_lines(path, category): global sum_line_count if os.path.isdir(path): for sub_dir in os.listdir(path): count_dir_files_code_lines(os.path.join(path, sub_dir), category) elif path[-len(category):] == category: # elif path[-2:] == "cs": sum_line_count += count_file_line(path) # print("当前计数:", sum_line_count) return sum_line_count if __name__ == '__main__': line_count = count_dir_files_code_lines("E:/ExecuSimu/ExecuDS10/Assets/Scripts", 'cs') print(line_count)
以上代码以C#文件为例,文件后缀为"cs",能够给出正确结果。
标签:count,__,项目,代码,计数,path,line,sum,dir From: https://www.cnblogs.com/zhaoke271828/p/16745983.html