2016-07-23 3 views
2

코드 라인을 계산할 프로젝트가 있습니다. 파이썬을 사용하여 프로젝트가 포함 된 파일 디렉토리의 모든 코드 줄 수를 계산할 수 있습니까?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 for line in 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

파이썬에 이미'len (file.readlines())'가 없습니까? 그리고 그것은 내가 아는 한 가지 방법 일뿐입니다. –

+0

그래도 작동 할 수 있다고 생각합니다. – Daniel

0

다음은 파이썬 패키지의 모든 코드 행을 계산하고 유익한 결과를 출력하기 위해 작성한 함수입니다. . 그것은

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   
관련 문제