import os
import chardet
# def detect(filename):
#
# content = open(filename,mode='rb') # str类型
# source_encoding = chardet.detect(content.read())['encoding']
# if source_encoding == 'utf-8':
# return True
# else:
# return False
def linecounter(filename):
print(filename)
# filename ='D:\desktopfile\RL code&paper\COP_RL_CL\POMO-master\POMO-master\NEW_py_ver\CVRP\POMO\CVRPEnv.py'
# file = open(file,'r')
if os.path.getsize(filename)==0:
return 0
content = open(filename, mode='rb') # str类型\
r = content.read()
r.decode(chardet.detect(r)['encoding'])
# print(r)
count = r.decode().count('\n')
content.close()
return count
#
# encode_method = 'utf-8'
# if chardet.detect(content.read())['encoding'] != 'utf-8':
# encode_method = 'ansi'
# content.close()
# if source_encoding == 'utf-8':
# with open(filename,'r',encoding='utf-8')as file:
# count = 0
# for line in file:
# # assert print(filename)
# count += 1
# # 一定要关闭文件
# file.close()
# else:
folderpath = os.getcwd()
# 打开一个文件,read权限
count = 0
for root, dirs, files in os.walk(folderpath):
if root!=folderpath:
# print("now counting: "+root) # 当前目录路径
for file in files:
if file[-3:] == '.py':
nowcount = (linecounter(root+"\\"+file))
print(file+" linecount: "+ str(nowcount))
count = count+ nowcount
print(count)
将代码放置在项目外运行即可