在上一篇的随笔中发表了代码统计小程序,但是发表后,我发现,以前写的代码怎么办
写了那么多,怎么就从0开始了呢,,,,我还是个孩子啊,不能这么残忍
于是,代码统计进阶版:统计当前目录下所有指定文件类型的行数
#coding:gbk import os import time from CountItem.FindCode import * n = 0 '''查找历史记录的行数''' try: with open('TotalLines','r') as p: lastline = '' for lastline in p.readlines(): pass index = lastline.find('>>') n = int(lastline[index+2:]) except ValueError as e: n = 0 except FileNotFoundError: n = 0 '''文件列表''' fileList = FindCode().getLocalfile(os.getcwd()) '''计算行数''' for filename in fileList: try: with open(filename,'r') as f: try: lines = f.readlines() except UnicodeDecodeError: '''编码错误,不用管,我们要的是行数''' '''嗯,,掩耳盗铃''' pass for s in lines: '''不计入空行''' if s == '\n': continue n += 1 except FileNotFoundError as e: print('文件名或文件路径错误,没有该文件!') os.system('pause') os._exit(1) except OSError as e: print('文件名不合法') os.system('pause') os._exit(1) print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + '代码行数>>' + str(n) + '\n') '''写入文件''' with open('TotalLines','a') as f: f.write(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + '代码行数>>' + str(n) + '\n') os.system('pause')
#coding:gbk import os class FindCode(): '''初始化查找的文件类型列表''' def __init__(self): self.targetFile = [] self.targetFile.append('c') self.targetFile.append('cpp') self.targetFile.append('py') self.targetFile.append('java') '''递归查找文件,用绝对路径''' def getLocalfile(self,findpath): fileList = os.listdir(findpath) aimsList = [] for filepath in fileList: filepath = findpath + '\\' + filepath if os.path.isdir(filepath): aimsList.extend(self.getLocalfile(filepath)) else: if self.selectFile(filepath): aimsList.append(filepath) return aimsList def selectFile(self,filepath): index = filepath.find('.') lastname = filepath[index+1:] return True if lastname in self.targetFile else False if __name__ == '__main__': Demo = FindCode() print('\n'.join(x for x in Demo.getLocalfile(os.getcwd())))
但是,不能统计一次挪一次窝吧,再改!
'''文件列表''' filepath = input('请输入指定文件路径(绝对路径):') if os.path.isdir(filepath): fileList = FindCode().getLocalfile(filepath)
这个就对了,很爽,,,