python 统计有效代码平均长度
时间: 2023-10-13 09:12:54 浏览: 36
可以使用以下代码来统计有效代码平均长度:
```python
import os
def count_code_lines(path):
total_lines = 0
code_lines = 0
for root, dirs, files in os.walk(path):
for file in files:
if file.endswith('.py'):
file_path = os.path.join(root, file)
with open(file_path, 'r', encoding='utf-8') as f:
lines = f.readlines()
total_lines += len(lines)
for line in lines:
if line.strip() and not line.strip().startswith('#'):
code_lines += 1
return total_lines, code_lines
path = './'
total_lines, code_lines = count_code_lines(path)
if code_lines > 0:
avg_length = total_lines / code_lines
print('有效代码平均长度为:%.2f' % avg_length)
else:
print('没有有效代码!')
```
注意:这只是一个简单的示例,实际上还需要考虑许多其他因素,如注释、空行等。