Py学习  »  Python

利用python看看你已经写了多少代码吧!

白胡子是这个世界上最猛的男人 • 3 年前 • 434 次点击  

十万代码,十万年薪!看看学习了这么久的你到底敲了多少代码吧!
在这里插入图片描述

这次我们运用到的是python 的 os
所谓os库就是Python标准库,包含几百个函数分为路径操作、进程管理、环境参数等几类,而我们今天要运用到的只是 os.path 子库。
在代码中我们要用到的几个函数分别是 :
os.path.isdir <来判断是否是文件夹>
os.listdir <来列出文件夹中的文件>
os.path.join <来拼接路径>
首先我们需要导入我们的os库

import os
  • 1
  • 1

由于我们要打开一个一个的文件夹,所以我采取的是递推,首先我们创建一个记录我们代码行数的代码并定义一个全局变量用来统计我们的行数

def CountFileLines(path):
	global count
  • 1
  • 2
  • 1
  • 2

在刚开始我们要判断我们文件是否是文件夹:如果是,我们则列出文件并进行递归

 if (os.path.isdir(path)):
        a = os.listdir(path)
        for i in a:
            path1 = os.path.join(path,i)
            CountFileLines(path1)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

那么如果是文件的话我们就要判断是否是以.py(我这里统计的是python的代码,如果统计别的语言请自行更改后缀),并且如果是py结尾的话我们就读取它的每一行直到结束

    elif path.endswith(".py"):
        count-=1 #设置count-1的原因是因为我这个判断会让每个代码的最后一个空行记入
        with open(path,encoding="utf-8") as f:
            while(True):
                line = f.readline()
                count+=1
                if not line:
                    break
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

在最后我们返回count 的值:

return count
  • 1
  • 1

大功告成!
最后附上完整代码:

import os
count = 0
def CountFileLines(path):
    global count
    if (os.path.isdir(path)):
        a = os.listdir(path)
        for i in a:
            path1 = os.path.join(path,i)
            CountFileLines(path1)
    elif path.endswith(".py"):
        count-=1
        with open(path,encoding="utf-8") as f: #这里的编码改为UTF-8(不然他好像默认GBK打不开)
            while(True):
                line = f.readline()
                count+=1
                if not line:
                    break
    return count
path = r'你想要计算代码的路径' #前面加上r 的作用是让计算机知道是一个路径信息
print(CountFileLines(path))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

最后希望各位程序员们在打代码的时候注意身体,尤其是疫情期间,我就因为身体原因就在学校被隔离了

在这里插入图片描述

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/74757
 
434 次点击  
文章 [ 1 ]  |  最新文章 3 年前