Python统计文件夹中代码的行数__os.walk()和os.listdir()

import os

#文件夹中既有文件件又有文件可以用os.walk(),而文件中只有文件可以用os.listdir()
def statLines_walk(path):
    total_count = 0
    #os.walk()方法,遍历路径下所有文件夹中的文件,返回的是一个三元组(root,dirs,files)
    #root 所指的是当前正在遍历的这个文件夹的本身的地址
    #dirs 是一个 list ,内容是该文件夹中所有的目录的名字(不包括子目录)
    #files 同样是 list , 内容是该文件夹中所有的文件(不包括子目录)
    #topdown --可选,为 True,则优先遍历 top 目录,否则优先遍历 top 的子目录(默认为开启
    for root, dirnames, filenames in os.walk(path, topdown=True):
        if len(filenames) > 0:
            for file in filenames:
                if file[-3:] == ".py":
                    fileLine_count = 0
                    with open(root + "/" + file, encoding = "utf-8") as fp:
                        data_lines = fp.readlines()
                        fp.close()

                    for line in data_lines:
                        #判断有效代码
                        if line == "\n":
                            continue
                        elif line.startswith("#"):
                            continue
                        else:
                            fileLine_count += 1
                            total_count += 1
                    print("'%s' 有效代码数是:%d"%(file, fileLine_count))

        
    print("整个文件下有效代码数是:%d"%total_count)

total_count = 0
def statLines_listdir(path):    
    try:
        files = os.listdir(path)#遍历path路径下的文件
    except FileNotFoundError as e:
        print(e)
    else:
        for file in files:
            #判断是否是文件夹
            if os.path.isdir(path + os.sep + file):
                statLines_listdir(path + os.sep + file)
            else:
                if file[-3:] == ".py":
                    fileLine_count = 0
                    with open(path + os.sep + file, encoding = "utf-8") as fp:
                        lines = fp.readlines()
                        fp.close()

                    for line in lines:
                        if line == "\n":
                            continue
                        elif line.startswith("#"):
                            continue
                        else:
                            fileLine_count += 1
                            global total_count
                            total_count += 1
                    print("%s 有效代码行数是:%d"%(file,fileLine_count))
        

if __name__ == '__main__':
    statLines_walk("C:/Users/Administrator/Desktop/data_for_selenium")
    print("*"*30)
    statLines_listdir("C:/Users/Administrator/Desktop/data_for_selenium")
    print(total_count)
            

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值