需求
统计某文件目录下的代码行数:
- 以“#”开头的有多少行
- 空行有多少行
- 正式代码有多少行
迭代实现1
from pathlib import Path
file_path = Path('C:\\Users\\keke\\PycharmProjects\\untitled')
file_p = Path('C:\\Users\\keke\\PycharmProjects\\untitled\\4moth\\425')
def countnum(x,count=[0,0,0]):
"""
This function to count how python lines i have wtite
"""
for file in x.iterdir():
if file.is_dir():
countnum(file) #recursive query,but we can not use “return conuntnum”,
#becase once we use it, return new function ,until return from first directory
#into last directory. so we can not use "return conuntnum(file)"
else:
with file.open(encoding='UTF-8') as f:
for lines in f:
if lines.startswith('#'):
count[0] += 1
elif lines.strip() == '':
count[1] += 1
else:
count[2] += 1
return count
print(countnum(file_p))
统配实现
通过通配符/*/.py 找出所有路径,然后迭代没有路径下的代码
目录树实现
通过生成路径树,直接迭代路径即可