import os
m_count=0
def Startcount(p_str_filename):
global m_count
print(p_str_filename)
f = open(p_str_filename, 'rb')
m = f.readlines()
m_line = len(m)
print(p_str_filename , " 文件行数 " , m_line)
m_count+=m_line
print("总的文件大小-》",m_count)
# 遍历文件夹
def walkFile(file):
for root, dirs, files in os.walk(file):
# root 表示当前正在访问的文件夹路径
# dirs 表示该文件夹下的子目录名list
# files 表示该文件夹下的文件list
# 遍历文件
for f in files:
m = os.path.join(root, f)
ss=os.path.splitext(m)
if ".cpp" == ss[1]:
Startcount(m)
# # 遍历所有的文件夹
# for d in dirs:
# print(os.path.join(root, d))
def main():
walkFile(r"E:\CODE\NewPrinter - 副本")
# Startcount(r"C:\test.txt")
if __name__ == '__main__':
main()
Python获取文件行数
遍历文件夹并统计.cpp文件行数
最新推荐文章于 2025-09-19 00:04:59 发布
这段代码定义了一个函数Startcount用于读取.cpp文件并统计行数,然后通过walkFile函数遍历指定文件夹下的所有子目录和文件,当遇到.cpp文件时调用Startcount进行统计。最后在main函数中对指定文件夹进行遍历。
800





