2016-07-23 86 views
2

我有一個項目的代碼行數要計算在內。是否可以通過使用Python來統計包含該項目的文件目錄中的所有代碼行?使用Python計算目錄中的代碼行

+0

使用['''os.walk'''(https://docs.python.org/3/library/os.html#os.walk)遍歷文件和子目錄,使用['''endswith'''](https://docs.python.org/3/library/std types.html#str.endswith)來過濾要計數的文件,打開每個文件並使用sum(1代表f中的行)'''來計算行數,聚合所有的文件行數。 – wwii

回答

3
from os import listdir 
from os.path import isfile, join 
def countLinesInPath(path,directory): 
    count=0 
    for line in open(join(directory,path), encoding="utf8"): 
     count+=1 
    return count 
def countLines(paths,directory): 
    count=0 
    for path in paths: 
     count=count+countLinesInPath(path,directory) 
    return count 
def getPaths(directory): 
    return [f for f in listdir(directory) if isfile(join(directory, f))] 
def countIn(directory): 
    return countLines(getPaths(directory),directory) 

要統計目錄中文件中的所有代碼行,請調用「countIn」函數,並將該目錄作爲參數傳遞。

+0

不是python已經有一個'len(file.readlines())'?這只是我知道的一種方式 –

+0

是的,我認爲這也可以工作,但這並不需要太多的代碼 – Daniel

0

這是我寫的一個函數,用於計算python包中的所有代碼行並打印信息輸出。它會計算所有行所有的.py

import os 

def countlines(start, lines=0, header=True, begin_start=None): 
    if header: 
     print('{:>10} |{:>10} | {:<20}'.format('ADDED', 'TOTAL', 'FILE')) 
     print('{:->11}|{:->11}|{:->20}'.format('', '', '')) 

    for thing in os.listdir(start): 
     thing = os.path.join(start, thing) 
     if os.path.isfile(thing): 
      if thing.endswith('.py'): 
       with open(thing, 'r') as f: 
        newlines = f.readlines() 
        newlines = len(newlines) 
        lines += newlines 

        if begin_start is not None: 
         reldir_of_thing = '.' + thing.replace(begin_start, '') 
        else: 
         reldir_of_thing = '.' + thing.replace(start, '') 

        print('{:>10} |{:>10} | {:<20}'.format(
          newlines, lines, reldir_of_thing)) 


    for thing in os.listdir(start): 
     thing = os.path.join(start, thing) 
     if os.path.isdir(thing): 
      lines = countlines(thing, lines, header=False, begin_start=start) 

    return lines 

要使用它,你只需要把這個目錄,你想在啓動例如,計算的代碼行中的一些包foo

countlines(r'...\foo') 

這將輸出類似:

 ADDED |  TOTAL | FILE    
-----------|-----------|-------------------- 
     5 |  5 | .\__init__.py  
     539 |  578 | .\bar.py   
     558 |  1136 | .\baz\qux.py   
相關問題