I have a project whose lines of code I want to count. Is it possible to count all the lines of code in the file directory containing the project by using Python?
Advertisement
Answer
JavaScript
x
21
21
1
from os import listdir
2
from os.path import isfile, join
3
4
def countLinesInPath(path,directory):
5
count=0
6
for line in open(join(directory,path), encoding="utf8"):
7
count+=1
8
return count
9
10
def countLines(paths,directory):
11
count=0
12
for path in paths:
13
count=count+countLinesInPath(path,directory)
14
return count
15
16
def getPaths(directory):
17
return [f for f in listdir(directory) if isfile(join(directory, f))]
18
19
def countIn(directory):
20
return countLines(getPaths(directory),directory)
21
To count all the lines of code in the files in a directory, call the “countIn” function, passing the directory as a parameter.