[Python] All the tests are over. Let's sit down and read a book. I want to count the number of lines of code I have written a few days ago. This afternoon, I spent some time to get it. The code is not very well written, let's take a look and try again later. [python] # _ * _ coding: utf_8 _ import OS import glob filefd = open('out.txt ', 'w') def countFileLines (filename): count = 0 try: handle = open (filename, 'R') for eachline in handle: count + = 1 TB t IOError, e: print 'file open error', e wstr = 'file: '+ str (filename) + 'has % d lines' % count print wstr filefd. write (str (Wstr) + '\ n') return count def folderCodeLines (folderpath): count = 0 filetype = ['*. py ','*. C ','*. cpp ','*. java '] # specifies the list of file types to be counted in for type in filetype: # print type # filefd. write (str (type) + '\ n') filepath = str (folderpath) +'/'+ str (type) for file in glob. glob (filepath): count + = countFileLines (file) if count! = 0: print folderpath, 'has code % d lines' % count # wstr = folderpath + 'has code % d lines' % count # filefd. write (str (wstr) + '\ n') return count ''' train of thought: for example, first enter algorithom, first calculate folderCodeLines (), then, use the list folder + '/' + str (L [I]) to constantly parse the string and merged path, and use the queue to traverse the directory tree hierarchy, every node in each layer calculates the folderCodeLines ''' def countCodeLines (startfolders): # startfolders = 'd:/study/practice/'queue = [] L = OS. listdir (startfolders) for I in r Ange (len (L): ndir = startfolders + '/' + str (L [I]) # print ndir filefd. write (str (ndir) queue. append (ndir) count = 0 while len (queue )! = 0: sdir = queue. pop () # print sdir if OS. path. isdir (sdir): L = OS. listdir (sdir) for I in range (len (L): ndir = sdir + '/' + str (L [I]) queue. append (ndir) count + = folderCodeLines (sdir) print count return count startfolders = 'd:/study/practice/'countcodelines (startfolders) def main (): # counting the number of lines of code for all specified types of files on the disk # startfolders = 'd:/study/practice/'dirs = ['d:/study/practice/', 'e: /', 'f:/'] for sdir in dirs: countCodeLines (sdir) # main ()