A simple example of python counting lines of code

  • 2020-06-01 10:03:18
  • OfStack

A simple example of python counting lines of code

When sent to the test, it was found that the number of lines of code needed to be counted

So I wrote a little program to count the number of lines of code.


#calclate_code_lines.py 
import os 
 
def afileline(f_path): 
  res = 0 
  f = open(f_path) 
  for lines in f: 
    if lines.split(): 
      res += 1 
  return res 
 
if __name__=='__main__': 
  host = 'E:'+os.sep+'develop'+os.sep+'dev_workspace'+os.sep+'AptanaStudio3'+os.sep+'webhost' 
   
  allfiles = 0 
  allline = 0 
     
  for root,dirs,files in os.walk(host): 
    for afile in files: 
       
      if(root.startswith(host+os.sep+'entries')): 
        continue 
      elif(root.startswith(host+os.sep+'.svn')): 
        continue 
      elif(root.startswith(host+os.sep+'.settings')): 
        continue 
      elif(root.startswith(host+os.sep+'logs')): 
        continue 
      elif(root.startswith(host+os.sep+'static')): 
        continue  
      elif(root.startswith(host+os.sep+'payload'+os.sep+'.svn')): 
        continue 
      elif(root.startswith(host+os.sep+'dist'+os.sep+'.svn')): 
        continue 
      elif(root.startswith(host+os.sep+'dsync'+os.sep+'.svn')): 
        continue 
      elif(root.startswith(host+os.sep+'hcache'+os.sep+'.svn')): 
        continue 
      elif(root.startswith(host+os.sep+'test'+os.sep+'.svn')): 
        continue 
      elif(root.startswith(host+os.sep+'webhost'+os.sep+'.svn')): 
        continue 
      elif(root.startswith(host+os.sep+'wsgi'+os.sep+'.svn')): 
        continue 
      elif(root.startswith(host+os.sep+'hcache'+os.sep+'templates'+os.sep+'.svn')): 
        continue 
      elif(root.startswith(host+os.sep+'dsync'+os.sep+'hcache'+os.sep+'.svn')): 
        continue 
      else:  
        ext = afile.split('.') 
        ext = ext[-1] 
        if (ext in ['py','css','js','html','txt','docx','wsgi']): 
          itpath = root+os.sep+afile 
          allfiles += 1 
          allline +=afileline(itpath) 
          print (root+os.sep+afile) 
           
  print ('Total: ',allfiles) 
  print ('Total lines:',allline) 

You can then transform this to facilitate later code statistics

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: