【Python】代码行数统计

两级目录,可扩展为N级。

 1 # Count the line of dir or file
 2 
 3 import os, fnmatch, fileinput
 4 
 5 def ChkFileType(lst):
 6     tmp = lst
 7     FileType = ['asm', 'c', 'cpp', 'h', 'ucf', 'v', 'java', 'm']
 8     for filename in tmp:
 9         flg = 1
10         for types in FileType:
11             if fnmatch.fnmatch(filename.lower(), "*."+types):
12                flg = 0
13                break
14         if (flg):
15             lst.remove(filename)
16 
17 def CountInsideFile(pathname):
18     if not os.path.exists(pathname):
19         print ("%s not exists." % pathname)
20         return -1
21     elif not os.path.isdir(pathname):
22         print ("%s not directory."  % pathname)
23         return -1
24     # Get the files and check the type
25     lst = os.listdir(pathname)
26     ChkFileType(lst)
27     # build a tuple for fileinput
28     filegp = tuple(pathname+filename for filename in lst)
29     
30     total = 0
31     with fileinput.input(files=filegp) as fin:
32         for line in fin:
33             total += 1
34     # Pay attention to close
35     fileinput.close()
36     print (total, pathname)
37     return total
38     
39 
40 if __name__ == "main":
41     desname = "count.txt"
42     En2Ch = {"compile":"编译原理",
43              "C":"C",
44              "C++":"C++",
45              "MIPS":"MIPS",
46              "NC4S":"NC4S",
47              "OS":"OS",
48              "pic":"计算机图形学",
49              "pattern":"模式识别",
50              "video":"视频标注",
51              "embed":"嵌入式",
52              "datastruct":"数据结构",
53              "database":"数据库",
54              "network":"网络",
55              "interface":"微机原理"}
56     # desname = sys.argv[1]
57     #if desname is None:
58     #    desname = count.txt
59     basename = "E:\python\"
60     fin = open(basename+desname, "w")
61     
62     ParrentPath = basename+"code\"
63     LstDir = os.listdir(ParrentPath)
64     print (LstDir)
65 
66     total = 0
67     for dirname in LstDir:
68         cnt = CountInsideFile(ParrentPath+dirname+"\")
69         if cnt<0:
70             break
71         fin.write("%-12s %8d
" % (dirname, cnt))
72         total += cnt
73     # write an blank line in the end
74     fin.write("%-12s %8d

" % ("total", total))
75     fin.close()
原文地址:https://www.cnblogs.com/bombe1013/p/3620787.html