方式1:
import os
length = 0
for root, dirs, files in os.walk('.'):
# root 当前所在的目录
# dirs 当前所在目录下的文件夹
# files 当前所在目录下的文件
for f in files:
if f.endswith('.html') or f.endswith('.py'):
# 因为只统计行数,读取使用rb模式,避免解码
with open(os.path.join(root, f), 'rb') as f:
length += len(f.readlines())
print(length)
find . -type f | grep -E '.py|.html' | xargs cat | wc -l
方式2:
- 采用递归实现
import os
def get_pyfile_line(path, suffix):
cnt = 0
for name in os.listdir(path):
fpath = os.path.join(path, name)
if os.path.isfile(fpath) and fpath.endswith(suffix):
with open(fpath, 'rb') as f:
fcnt = len(f.readlines())
cnt += fcnt
print(fpath, fcnt, cnt)
elif os.path.isdir(fpath):
cnt += get_pyfile_line(fpath, suffix)
return cnt
print(get_pyfile_line('.', '.py'))
find ./ -name "*.py" | xargs cat | wc -l