python计算文件代码文件总行数

介绍

    为了计算项目中指定项目或者总项目的文件行数,特写了一个简单Python脚本来计算指定文件夹下的.cpp、.c、.h、.hpp、.cc等文件的总行数(不包含空行)。

实现

def get_file_line(the_file):
	lines = 0
	try:
		with open(the_file, "rb") as file_handle:
			for each_line in file_handle:
				each_line = each_line.strip()
				if each_line:
					lines += 1
	except IOError as err:
		pass

	return lines

    计算指定文件的总行数,不计算空行,但是计算了注释,如果不需要注释的话,可能处理起来就需要复杂些。

def calc(path):
	total_lines = 0

	for item in os.listdir(path):
		try:
			sub_path = os.path.join(path, item)
			mode = os.stat(sub_path)[stat.ST_MODE]
		except IOError as err:
			s = sys.exc_info()
			print("Error '%s' happened on line %d" % (s[1], s[2].tb_lineno))
			pass
		except ValueError:
			pass

		if stat.S_ISDIR(mode):
			total_lines += calc(sub_path)
		else:
			if sub_path.endswith(".cpp") or sub_path.endswith(".h") or sub_path.endswith(".c") or sub_path.endswith(".hpp") \
					or sub_path.endswith(".cc"):
				total_lines += get_file_line(sub_path)

	return total_lines

    计算时,则是遍历目录,计算指定文件的行数。

def walk(path):
	total_lines = 0
	mode = os.stat(path)[stat.ST_MODE]
	if stat.S_ISDIR(mode):
		total_lines = calc(path)
	else:
		total_lines = get_file_line(path)

	return total_lines

    输入路径时,首先判断是否是文件或者是目录。

if len(sys.argv) != 2:
    current_path = os.getcwd()
else:
    current_path = sys.argv[1]

the_path = current_path
print(the_path)
file_lines = walk(the_path)
print(file_lines)

try:
	with open("count.txt", "w") as data:
		print(file_lines, file = data)
except IOError as err:
	print("open file count.txt error.")
	pass

    如果没有输入路径,则默认为脚本路径,结果输出到count.txt文件当中。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Z小偉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值