功能
统计一个文件夹中所有指定后缀名文件中的数据行数
应用场景
统计项目代码行数
代码
# coding=utf-8
import os
def get_line_counts(path, file_types, include_blank_line=True):
"""
path:str:文件夹全路径
file_types:tuple or list:要统计的文件后缀列表:如['py', 'cpp', 'java']
include_blank_line:bool:空行是否也计入总的统计行数中
"""
total_lines = 0
for parent, _, filenames in os.walk(path): # 遍历path下的所有子文件夹
for filename in filenames: # 遍历文件夹下的所有文件
file_type = filename.split('.')[-1] # 获取文件后缀名
if file_type in file_types:
file_full_path = os.path.join(parent, filename) # 获取文件的全路径
if not include_blank_line:
for line in open(file_full_path).readlines():
if len(line.strip()) != 0:
total_lines += 1
else:
total_lines += len(open(file_full_path).readlines())
return total_lines
用例
line_count = get_line_counts(r"C:\Users\Administrator\Desktop\my_python_tools", ['py'])