統計目錄下全部的代碼個數和總行數。json
# -*- 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()