使用python对文件夹里面所有代码行数进行统计。

统计目录下所有的代码个数和总行数。

 

# -*- coding: utf-8 -*-
# @Author  : ydf
import json
import os
from pathlib import Path
from collections import OrderedDict
from app.utils_ydf import LoggerMixin


class CodeStatistics(LoggerMixin):
    def __init__(self, root_dir: str = None, file_suffix_tuple=('.py',)):
        self.root_dir = root_dir or Path(__file__).parent.parent
        self._file_suffix_tuple = file_suffix_tuple
        self.file_name__file_line_map = dict()
        self._total_lines = 0

    def _find_all_files(self):
        """
        查到所有符合条件的文件
        :return:
        """
        for parent, dirnames, filenames in os.walk(self.root_dir):
            for filename in filenames:
                ext = filename.split('.')[-1]
                if '.' + ext in self._file_suffix_tuple:
                    self.file_name__file_line_map[os.path.join(parent, filename)] = 0

    def _conunt_file_line(self, file_name):
        """
        计算一个文件的代码行数
        :param file_name:
        :return:
        """
        for file_line in open(file_name, encoding='utf8').readlines():
            if file_line != '' and file_line != '\n':  # 过滤掉空行
                self.file_name__file_line_map[file_name] += 1
                self._total_lines += 1

    def start_statistics(self):
        self._find_all_files()
        for file_name in self.file_name__file_line_map:
            self._conunt_file_line(file_name)
        self.logger.debug(json.dumps(self.file_name__file_line_map, indent=4))
        ordered_dict = OrderedDict()
        for k, v in sorted(self.file_name__file_line_map.items(), key=lambda itemx: itemx[1], reverse=True):
            ordered_dict[k] = v
        self.logger.info(json.dumps(ordered_dict, indent=4))
        self.logger.info(f'文件夹{self.root_dir} 里面一共有 {len(self.file_name__file_line_map)} 个以 {self._file_suffix_tuple} 为后缀的代码文件,总行数是 {self._total_lines}')
        return len(self.file_name__file_line_map), self._total_lines


if __name__ == '__main__':
    CodeStatistics().start_statistics()

 

转载于:https://www.cnblogs.com/ydf0509/p/10800451.html

你可能感兴趣的:(使用python对文件夹里面所有代码行数进行统计。)