听说简历要求10万行代码经验。于是写了个Python脚本用来计算电脑磁盘内代码的行数。
主要功能:
①统计指定代码的总行数
②统计每个代码单独的行数
③自定义设置存储路径
设计思路:
将文件转化为txt文档,对txt文档统计行数。
非GUI代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
import shutil import os path = "C:\\Users\\dell\\Desktop\\archives\\" file_path1 = "E:\\Temporary\\python\\" file_path2 = "E:\\Files\\University study\\SE\\" file_archive = [] file_archive.append(file_path1) file_archive.append(file_path2) file_label = [".py", ".h", ".c", ".cpp", ".java", ".m"] counter = 1 total_line = 0 def calculate(filename): global counter global total_line newName = path + filename[filename.rfind('\\')+1:filename.rfind('.')] + str(counter) + ".txt" # 更改文件后缀名为txt shutil.copyfile(filename, newName) # 将文件拷贝到工作区 myfile = open(newName, 'rb') # 以rb方式打开文件 lines = len(myfile.readlines()) # 计算单个文件的行数 total_line += lines # 加入到总行数 counter += 1 # 计数器加1 def visitDir(path): global file_label if not os.path.isdir(path): print('Error: "', path, '" is not a directory or does not exist.') return else: try: for lists in os.listdir(path): sub_path = os.path.join(path, lists) flag = 0 for i in range(len(file_label)): if file_label[i] == sub_path[sub_path.rfind("."):]: flag = 1 break if flag == 1: calculate(sub_path) if os.path.isdir(sub_path): visitDir(sub_path) except: pass if __name__ == '__main__': x = 0 for i in range(len(file_archive)): visitDir(file_archive[i]) # visitDir(file_path2) print("文件数:", counter, "\n总行数:", total_line) |
效果图:
GUI程序下载地址:https://download.csdn.net/download/xyisv/10317619