本文實例為大家分享了python中的代碼行數統計,供大家參考,具體內容如下
思路: 統計文件中代碼的總行數減去空行單行注釋以及多行注釋
功能:
1.獲取文件內容的總行數
2.排除空行 單行注釋 多行注釋
def code_statistics(path):
# # 打開這個文件
with open(path, 'r', encoding='utf-8') as openFile:
# 按列讀取
fileline = openFile.readlines()
# 給非代碼行一個變量
i = 0
# 整個文件里面內容的總行數
number_line = len(fileline)
# 給多行注釋一個狀態
note = False
# 遍歷文件內容
for line in fileline:
# 空行
if line == '\n':
i += 1
# 單行注釋
elif re.findall('[#]', line):
i += 1
# 多行注釋開頭
elif re.findall("\'\'\'", line) and note == False:
i += 1
note = True
# 多行注釋結尾
elif re.findall("\'\'\'", line) and note == True:
i += 1
note = False
# 多行注釋內部注釋
elif note:
i += 1
num_code_line = number_line - i
print(num_code_line)
如果統計文件夾中的python文件的代碼行數,首先就是要遍歷文件目錄,篩選出以.py結尾的文件,再去統計py文件里面的代碼行數
def get_all_fire(path):
# 得到當前目錄下的所有文件
file_list = os.listdir(path)
py_file_abs = []
# 遍歷所有文件
for file_name in file_list:
# 獲取文件及文件夾的絕對路徑
file_abs = os.path.join(path, file_name)
if os.path.isfile(file_abs) and file_name.endswith('.py'): # 判斷當前文件路徑是否是文件和.py文件
py_file_abs.append(file_abs)
# 判斷當前文件路徑是不是文件夾
elif os.path.isdir(file_abs):
py_file_abs += get_all_fire(file_abs)
return py_file_abs
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

