通信人家园
标题:
Python
[查看完整版帖子]
[打印本页]
时间:
2021-9-16 10:42
作者:
落月成孤倚
标题:
Python
python实现递归统计指定目录下,指定后缀名文件的行数:
import os
def countLine(filename):
fp = open(filename, 'r+',encoding = 'utf-8')
line_count = 0
for line in fp.readlines():
if not line.split(): # 判断是否为空行
line.strip() # 去除空行
continue
else:
line_count += 1
fp.close()
return line_count
复制代码
def listdir(dir):
files = os.listdir(dir) #列出目录下的所有文件和目录
for file in files:
filepath = os.path.join(dir, file)
# print("filename " + filepath)
if os.path.isdir(filepath): #如果filepath是目录,递归遍历子目录
listdir(filepath)
elif os.path: #如果filepath是文件,直接统计行数
file_type = file.split('.') # 只统计规范命名文件:[文件名.扩展名]
if len(file_type) > 1 :
if file_type[1] in ["js", "css", "hml", "json"]: # 要统计的文件后缀名
line = countLine(filepath)
dirStr._count = dirStr._count + line
print("filename " + filepath + " lines is " + str(line))
复制代码
通信人家园 (https://www.txrjy.com/)
Powered by C114