递归统计某目录下文本行数

需求

统计某文件目录下的代码行数:

  • 以“#”开头的有多少行
  • 空行有多少行
  • 正式代码有多少行

迭代实现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 找出所有路径,然后迭代没有路径下的代码

目录树实现

通过生成路径树,直接迭代路径即可

对比优势

扩展使用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值