python--代码统计(进阶版)
2024-08-31 03:10:06
在上一篇的随笔中发表了代码统计小程序,但是发表后,我发现,以前写的代码怎么办
写了那么多,怎么就从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)
这个就对了,很爽,,,
最新文章
- PCA、ZCA白化
- CSS3制作动画的三个属性
- [转]Oracle中使用Rownum分页详细例子
- 804 pretest 解题
- TableViewCell自适应高度
- hello, angular
- Linux数据流重定向
- Java基础知识强化之IO流笔记38:字符流缓冲流之BufferedWriter / BufferedReader使用
- Android之sqlite 命令
- python分布式抓取网页
- remote: Permission to user_name/Code.git denied to other_user_name. fatal: unable to access 'https://github.com/user_name/Code.git/': The requested URL returned error: 403
- Python 包管理(PYPA)
- 聊聊JVM(二)说说GC的一些常见概念
- Python GUI之tkinter窗口视窗教程大集合(看这篇就够了)
- https搭建实例
- 使用parted对大于2T的磁盘进行分区
- 《转》Java与Http协议
- 通过Stetho在Chrome上调试Android App
- jsp 中 , jq 获取当前所点击的 select 的 id 值的注意事项
- truffle Dapp 搭建