#encoding = utf-8
import os
def get_python_file_abspath(dirpath,all_files = []):
'''获取指定文件夹下python文件名'''
#先判断指定的路径是文件还是目录
if os.path.isdir(dirpath):#是目录,而且此目录存在
files = os.listdir(dirpath)#列出此目录下所有的子文件和子目录
for file in files:
file_path = os.path.join(dirpath, file)#绝对路径拼接
get_python_file_abspath(file_path)#不加return,否则all_files中只会有一个元素
elif os.path.isfile(dirpath) and os.path.splitext(dirpath)[1] == '.py':#文件存在
all_files.append(dirpath)
return all_files
def get_file_code_lines(filename):
'''统计输入的文件中有效的代码行数'''
code_lines = 0
with open(filename,encoding = 'ISO-8859-1') as fp:
lines = fp.readlines() #读取所有的内容放到列表中
## print(len(lines))
for line in lines:
line = line.strip()
if line and line[:3]!="'''" and line[0]!='#':#过滤掉注释
code_lines +=1
return code_lines
if __name__=='__main__':
filename = r'F:\'
result = 0
for file in get_python_file_abspath(filename):
num = get_file_code_lines(file)
print('%s文件中有效代码行数为:%d'%(file,num))
result += num
print('*'*40)
print('%s目录下所有文件的有效代码行数为:%d'%(filename,result))
print('*'*40)