美文网首页
实现python中的代码行数统计思路:

实现python中的代码行数统计思路:

作者: 叶_叶 | 来源:发表于2018-03-16 14:18 被阅读0次

    实现python中的代码行数统计思路:

    统计文件中代码的总行数减去空行单行注释以及多行注释功能:

    1.获取文件内容的总行数

    2.排除空行 单行注释 多行注释

    def code_statistics(path):      

    # # 打开这个文件      

    with open(path, 'r', encoding='utf-8') as openFile:          

    # 按列读取          

    fileline = openFile.readlines()          

    # 给非代码行一个变量          

    i = 0          

    # 整个文件里面内容的总行数       number_line = len(fileline)          

    # 给多行注释一个状态          

    note = False          

    # 遍历文件内容         

     for line in fileline:             

     # 空行              

    if line == '\n':                  

    i += 1              

    # 单行注释             

    elif re.findall('[#]', line):                  

    i += 1             

     # 多行注释开头             elif re.findall("\'\'\'", line) and note == False:                  

    i += 1                  

    note = True              

    # 多行注释结尾             elif re.findall("\'\'\'", line) and note == True:                  

    i += 1                 

     note = False              

    # 多行注释内部注释            

     elif note:                  

    i += 1          

    num_code_line = number_line - i          

    print(num_code_line)  

    如果统计文件夹中的python文件的代码行数,首先就是要遍历文件目录,筛选出以.py结尾的文件,再去统计py文件里面的代码行数

    def get_all_fire(path):      

    # 得到当前目录下的所有文件    file_list = os.listdir(path)      

    py_file_abs = []      

    # 遍历所有文件      

    for file_name in file_list:          

    # 获取文件及文件夹的绝对路径          

    file_abs = os.path.join(path, file_name)          

    if os.path.isfile(file_abs) and file_name.endswith('.py'): # 判断当前文件路径是否是文件和.py文件              

    py_file_abs.append(file_abs)              

    # 判断当前文件路径是不是文件夹          

    elif os.path.isdir(file_abs):              

    py_file_abs += get_all_fire(file_abs)      

    return py_file_abs   


    相关文章

      网友评论

          本文标题:实现python中的代码行数统计思路:

          本文链接:https://www.haomeiwen.com/subject/uscufftx.html