The Addhosts project is nearing the end, and I would like to know how many lines of code we have written.
First, the demand
The number of code lines for the py file in the source directory.
650) this.width=650; "src=" Https://s3.51cto.com/oss/201711/15/16a2284fa7175bc6f107b02959024ff6.png "title=" Codedir.png "alt=" 16a2284fa7175bc6f107b02959024ff6.png "/>
Second, the script analysis
Gets all the. py files in the specified directory, traversing the files;
Read each file, traverse the contents of the file, filter out empty lines and comments;
III. realization and Results
#coding: Utf-8import osclass statlines (object): def __init__ (Self,path): self.path = path def Stat_lines (self): file_list = os.listdir (Self.path) os.chdir (Self.path) total = 0 for file in file_list: if file.endswith ('. Py '): lines = Open (file, encoding= ' utf-8 '). ReadLines () count = 0 for line in lines: if line == ' \ n ': continue elif line.startswith (' # '): continue else: count += 1 total += count print ('%s has %d lines ' % (file,count)) print (' total lines is: %d ' %total) if __name__ == ' __main__ ': sl = statlines (' E:\\Python_Project\\addhost _v2\\addhosts ') sl.stat_lines ()
The results of the operation are as follows:
650) this.width=650; "src=" Https://s3.51cto.com/oss/201711/15/cc2ac41637ba3f31728df8ad7e07162a.png "title=" Results.png "alt=" Cc2ac41637ba3f31728df8ad7e07162a.png "/>
Iv. Summary
Questions:
The following error was encountered while executing open (file). ReadLines ()
"Unicodedecodeerror: ' GBK ' codec can ' t decode byte 0xaf in position 548:illegal multibyte sequence"
Workaround:
After setting encoding= ' Utf-8 ' in open, the problem is resolved.
This article is from the "Le Gakuen" blog, please be sure to keep this source http://2338053.blog.51cto.com/2328053/1982133
Count Python code lines