Translation Notice
This article was machine-translated using DeepSeek-R1.
- Original Version: Authored in Chinese by myself
- Accuracy Advisory: Potential discrepancies may exist between translations
- Precedence: The Chinese text shall prevail in case of ambiguity
- Feedback: Technical suggestions regarding translation quality are welcomed
Preface
Recently I suddenly wanted to know how many lines of code I’ve written, so I created this little tool…
Preparation
First consider the desired output:
Language | Lines | Size | Files |
---|---|---|---|
A | 12345 | 300 KB | 193 |
B | 2345 | 165 KB | 98 |
The program outputs a table sorted by code lines.
Basic code framework:
|
|
Now let’s move to the ==core implementation==
Implementation
File Scanning
First, we need to get file lists under root directory using os.walk
:
os.walk(rootdir)
returns a walker (iterable) containing file/directory lists for each subdirectory. Example:
For folder structure:
|
|
Running:
|
|
Output:
|
|
First element is current root, second is subdirectories, third is files.
Implementation code:
|
|
Sample output (manually formatted):
|
|
Next step: actual line counting.
Line Counting
Empty lines shouldn’t be counted. Modify line 23:
|
|
But when running:
|
|
Some files use GBK
encoding. Improved code:
|
|
Now correct results:
|
|
Final step: table formatting.
Table Formatting
Use PrettyTable
library:
|
|
Output:
|
|
Conclusion
Final code (without comments):
|
|
Future improvements:
- Add regex file ignore
matplotlib
visualizationPyQt5
GUI- … (Welcome valuable suggestions!)