gpt4 book ai didi

python - 使用 Python 计算目录中的代码行数

转载 作者:太空狗 更新时间:2023-10-30 01:41:26 25 4
gpt4 key购买 nike

我有一个项目,我想计算其代码行数。是否可以用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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com