我有一個項目的代碼行數要計算在內。是否可以通過使用Python來統計包含該項目的文件目錄中的所有代碼行?使用Python計算目錄中的代碼行
2
A
回答
3
from os import listdir
from os.path import isfile, join
def countLinesInPath(path,directory):
count=0
for line in open(join(directory,path), encoding="utf8"):
count+=1
return count
def countLines(paths,directory):
count=0
for path in paths:
count=count+countLinesInPath(path,directory)
return count
def getPaths(directory):
return [f for f in listdir(directory) if isfile(join(directory, f))]
def countIn(directory):
return countLines(getPaths(directory),directory)
要統計目錄中文件中的所有代碼行,請調用「countIn」函數,並將該目錄作爲參數傳遞。
+0
不是python已經有一個'len(file.readlines())'?這只是我知道的一種方式 –
+0
是的,我認爲這也可以工作,但這並不需要太多的代碼 – Daniel
0
這是我寫的一個函數,用於計算python包中的所有代碼行並打印信息輸出。它會計算所有行所有的.py
import os
def countlines(start, lines=0, header=True, begin_start=None):
if header:
print('{:>10} |{:>10} | {:<20}'.format('ADDED', 'TOTAL', 'FILE'))
print('{:->11}|{:->11}|{:->20}'.format('', '', ''))
for thing in os.listdir(start):
thing = os.path.join(start, thing)
if os.path.isfile(thing):
if thing.endswith('.py'):
with open(thing, 'r') as f:
newlines = f.readlines()
newlines = len(newlines)
lines += newlines
if begin_start is not None:
reldir_of_thing = '.' + thing.replace(begin_start, '')
else:
reldir_of_thing = '.' + thing.replace(start, '')
print('{:>10} |{:>10} | {:<20}'.format(
newlines, lines, reldir_of_thing))
for thing in os.listdir(start):
thing = os.path.join(start, thing)
if os.path.isdir(thing):
lines = countlines(thing, lines, header=False, begin_start=start)
return lines
要使用它,你只需要把這個目錄,你想在啓動例如,計算的代碼行中的一些包foo
:
countlines(r'...\foo')
這將輸出類似:
ADDED | TOTAL | FILE
-----------|-----------|--------------------
5 | 5 | .\__init__.py
539 | 578 | .\bar.py
558 | 1136 | .\baz\qux.py
相關問題
- 1. 使用Python計算目錄的大小?
- 2. Python計算器代碼
- 3. 在Python或Bash中計算代碼行數的實用程序
- 4. 使用python計算目錄上的文件記錄
- 5. 使Python在我的目錄中使用代碼(不在/ usr/...中)
- 6. 如何使用Python計算目錄中的文件數
- 7. 如何計算使用while循環的python代碼中的條目數?
- 8. 計算python中的代碼的計算時間和內存
- 9. 如何計算目錄及其子目錄中所有文件中的代碼行數
- 10. 如何計算PHP項目中的代碼行數?
- 11. 如何計算整個項目中的代碼行總數?
- 12. 由設計人員運行的代碼中的相對目錄
- 13. 計算的代碼
- 14. 計算目錄數
- 15. 用於在android中計算的代碼
- 16. 計算Python中素數的總和 - 這行代碼的用途是什麼?
- 17. 目錄中的使用Python
- 18. 使用Python代碼計算代表集合A上關係R的矩陣中的非零條目
- 19. 在python項目中統計源代碼行
- 20. 如何編寫使用GPU執行計算的代碼?
- 21. 運行源代碼中使用Unicode字符的Python 2.7代碼
- 22. 當Python計算另一段代碼時,是否可以運行一些代碼?
- 23. 計算使用python的
- 24. 如何在簡單的Julia代碼中使用@everywhere宏進行並行計算
- 25. 用於計算後臺代碼和aspx文件中代碼行數的工具?
- 26. 使用Python進行計算請求sql
- 27. 如何計算使用bash的路徑中的目錄數量?
- 28. PHP - 如何計算應用程序中的代碼行數
- 29. 並行C代碼距離計算
- 30. 如何計算代碼行數?
使用['''os.walk'''(https://docs.python.org/3/library/os.html#os.walk)遍歷文件和子目錄,使用['''endswith'''](https://docs.python.org/3/library/std types.html#str.endswith)來過濾要計數的文件,打開每個文件並使用sum(1代表f中的行)'''來計算行數,聚合所有的文件行數。 – wwii