统计文件代码行数
import os """ 根据命令行输入的统计目录及文件类型进行统计目录或单个文件的代码行数 """ def count_all_file_code(count_path,file_types=[]): #判断传入文件是否为空 if len(file_types)==0: file_types=[".txt",".asp",".php",".h",".cpp",".c",".py"] #存储所有文件总代码量 total_line_number=0 file_line_number=0 #存储每个文件及代码量 file_lines_dict={} #判断目录或文件是否存在 if not os.path.exists(count_path): print("输入的目录或者文件不存在") #判断是否是文件 if os.path.isfile(count_path): file_type=os.path.splitext(count_path)[1] #如果文件在指定文件类型中 if file_type in file_types: total_line_number=count_sigle_file_code(count_path) #单个文件及代码量写入字典 file_lines_dict[count_path]=total_line_number #返回文件及代码量及文件字典 return "文件%s代码行:%d"%(count_path,total_line_number) #判断是否是目录 elif os.path.isdir(count_path): #遍历目录下所有的文件 for root,dirs,files in os.walk(count_path): for file in files: #拼接出单个文件的绝对路径 file_path=os.path.join(root,file) #获取文件类型 file_type=os.path.splitext(file_path)[1] if file_type in file_types: #统计每个文件的代码量 file_line_number=count_sigle_file_code(file_path) total_line_number+=file_line_number #单个文件及代码量写入字典 file_lines_dict[file_path]=file_line_number return "总文件代码行数:%d\n 每个文件的代码行:%s"%(total_line_number,file_lines_dict) def count_sigle_file_code(file_path): #记录单个文件代码量 line_number=0 #用于标记是否要记录多行注释代码行,True代码 flag=True #获取编码格式 try: fp=open(file_path,encoding="utf-8") fp.read() encoding_type="utf-8" except: encoding_type="gbk" finally: fp.close() #打开文件统计代码 with open(file_path,encoding=encoding_type) as file_obj: for line in file_obj: #去除每行文件两端的空白 line=line.strip() #如果已三引号开头且flag==False,需要把flag置为True,证明跳出多行注释了 #同时跳过本行,不统计 if line.startswith('"""') and flag==True: flag=False continue #flag==False证明在多行注释内部,跳过不统计 elif flag==False: continue #如果已三引号开头且flag==False,需要把flag置为True,证明跳出多行注释了 elif line.endswith('"""') and flag==False: flag=True continue #记录文件编码声明行 elif line.startswith("#encoding") or line.startswith("#coding") or line.startswith("#-*-"): line_number+=1 #空行跳过不统计 elif line=="": continue #单行注释跳过不统计 elif line.startswith("#"): continue #在一行的三引号注释跳过,不统计,以三引号开头且此行不等于三引号 elif line.startswith('"""') and line.endswith('"""') and line!='"""': continueelse: line_number+=1 return line_number #print(count_all_file_code("e:\\gr\\test",file_types=[])) if __name__=="__main__": import sys if len(sys.argv)<2: print("请输入要统计的文件目录") sys.exit() count_path=sys.argv[1] file_types=[] if len(sys.argv)>2: for file_type in sys.argv[2:]: file_types.append(file_type) print(count_all_file_code(count_path,file_types))