介绍
为了计算项目中指定项目或者总项目的文件行数,特写了一个简单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文件当中。