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)