Python统计代码行数的实现方法
本文介绍如何使用Python脚本统计指定目录下的代码文件行数,功能涵盖总行数、空行及注释行的识别。通过遍历文件并逐行读取,利用字符串处理方法判断行类型,最终输出各类型统计结果,适用于快速评估代码规模。
具体实现代码参考如下示例:
import os
import string
path = "/Users/U/workspace/python learning/show-me-the-code/0007/test/"
dir = os.listdir(path)
def count(file):
total = 0 #总行数
countPound = 0 #注释行数
countBlank = 0 #空行数
line = open(file,'r',encoding='utf-8') #打开文件,因为注释有中文所以使用utf-8编码打开
for li in line.readlines(): #readlines()一次性读完整个文件
total += 1
if not li.split(): #判断是否为空行
countBlank +=1
li.strip()
if li.startswith('#'):
countPound += 1
print(file)
print("countBlank:%d" % countBlank)
print("countPound:%d" % countPound)
print("total:%d" % total)
for file in dir:
count(path + file)
上述关于使用Python统计代码行数的示例(涵盖空行及注释统计)即为完整分享内容,旨在为读者提供实用参考,欢迎大家收藏与支持。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













