Python counts the number of lines in the disk code file

Keywords: Python Java Apache

I heard that the resume requires 100000 lines of code experience. So I wrote a Python script to calculate the number of lines of code in the computer disk.

Main functions:

① Count the total number of lines of the specified code
② Count the individual lines of each code
③ Custom settings storage path

Design idea:

Convert the file to a TXT document, and count the lines of the txt document.

Non GUI code:

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"  # Change the file suffix to txt
    shutil.copyfile(filename, newName)  # Copy files to workspace
    myfile = open(newName, 'rb')  # Open file in rb mode
    lines = len(myfile.readlines())  # Calculate the number of lines in a single file
    total_line += lines  # Add to total row
    counter += 1  # Counter plus 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("Number of documents:", counter, "\n Total number of banks:", total_line)

Design sketch:

GUI program download address: https://download.csdn.net/download/xyisv/10317619

More Python content access omegaxyz.com
All codes of the website are authorized by Apache 2.0
Website articles are authorized by knowledge sharing license agreement BY-NC-SA4.0
Copyright © 2018 OmegaXYZ - reprint please indicate the source

Posted by paulytrick on Fri, 03 Apr 2020 00:12:18 -0700