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))