Skip to content

Commit 11db6ec

Browse files
robot527cailurus
authored andcommitted
add 0007(count one file omitting multiple-line comment)
1 parent 3fd48b0 commit 11db6ec

1 file changed

Lines changed: 51 additions & 0 deletions

File tree

‎robot527/0007/count_codes.py‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
#! usr/bin/python3
2+
"""
3+
第 0007 题:有个目录,里面是你自己写过的程序,统计一下你写过多少行代码。
4+
包括空行和注释,但是要分别列出来。
5+
"""
6+
7+
class PyfileInfo:
8+
9+
def __init__(self, file):
10+
self.file_name = file
11+
self.total_line_num = 0
12+
self.blank_line_num = 0
13+
self.comment_line_num = 0
14+
15+
def count_lines(self):
16+
if self.file_name[-3:] != '.py':
17+
print(self.file_name + ' is not a .py file!')
18+
return
19+
try:
20+
with open(self.file_name) as code:
21+
for each_line in code:
22+
self.total_line_num += 1
23+
temp = each_line.strip()
24+
if temp == '':
25+
self.blank_line_num += 1
26+
elif temp[0] == '#':
27+
self.comment_line_num += 1
28+
29+
except IOError as err:
30+
print('File error: ' + str(err))
31+
32+
import os
33+
target_path = '.'
34+
file_list = [f for f in os.listdir(target_path)
35+
if os.path.isfile(os.path.join(target_path, f))]
36+
#print(file_list, len(file_list))
37+
38+
pyfile_list = [os.path.join(target_path, f) for f in file_list
39+
if f[-3:] == '.py']
40+
41+
print(pyfile_list[0])
42+
43+
pyf1 = PyfileInfo(pyfile_list[0])
44+
pyf1.count_lines()
45+
#pyf2 = PyfileInfo('test.c')
46+
#pyf2.count_lines()
47+
48+
print('==' * 18)
49+
print('Total line number is:', pyf1.total_line_num)
50+
print('Blank line number is:', pyf1.blank_line_num)
51+
print('Comment line number is:', pyf1.comment_line_num)

0 commit comments

Comments
 (0)