Python递归遍历目录统计并合并Py文件代码行数

听雨眠
听雨眠
发布时间:2026-10-13 | 2人浏览过
原创

本文介绍使用Python递归遍历指定目录,筛选后缀为.py的文件,并统计总代码行数的方法。通过os.listdir结合递归调用实现目录遍历,利用字符串切片判断文件后缀,最终将所有Python文件内容合并写入单一文件,适用于统计个人项目代码总量的场景。

大学毕业之际,为了回顾大学期间的学习成果,需要统计总共编写了多少行代码。

#coding=utf-8
import os
class Solution:
 def __init__(self):
  self.dirPath = []
 
 def numberOfCode(self,path):
  for dir in os.listdir(path):
   childDir = os.path.join(path,dir)
   if os.path.isdir(childDir):
    self.numberOfCode(childDir)
   else:
    if childDir[-2:] == "py":
     self.dirPath.append(childDir)
  return self.dirPath
 
 def setCode(self):
  with open("/home/code.py","ab+") as f:
   for file in self.dirPath:
    content = open(file,"r").read()
    f.write(content)
s = Solution()
s.numberOfCode("/home/py/")
s.setCode()

以上关于Python遍历文件夹并找出后缀为.py文件的方法即为完整分享,希望能为读者提供参考,同时也欢迎大家继续支持本站。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表