我有一个项目,我想计算其代码行数。是否可以用Python统计项目所在文件目录下的所有代码行数?
最佳答案
这是我编写的一个函数,用于计算 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
关于python - 使用 Python 计算目录中的代码行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38543709/