Python calculates the number of file types specified by all files in a directory (including all files in subdirectories)

Enter the project name to calculate the number of files in C + +, Java, python, GO languages in a project, and find out the file name of the largest file in Python file

1. First read the file address and find the folder

import os
import os.path
path = 'C:/python Study/Python task/' + input("Please enter the project name:")

2. Assign an initial value to the number of these four file types, and create two lists to store the file size and file name of a file type (separate for better understanding)

cppnum = 0
javanum = 0
pynum = 0
gonum = 0
list_size = []
list_name = []

3. Count the number of these four file types (and store the name and size of Python files in the list)

for parentdir, dirname, filenames in os.walk(path):
    for filename in filenames:
        if os.path.splitext(filename)[1] == '.cpp':
            cppnum = cppnum + 1
        if os.path.splitext(filename)[1] == '.java':
            javanum = javanum + 1
        if os.path.splitext(filename)[1] == '.py':
            pynum = pynum + 1
            filesize = os.path.getsize(os.path.join(parentdir,filename))
        if os.path.splitext(filename)[1] == '.go':
            gonum = gonum + 1

4. Convert saved file size (customize a function)

def getsizename(size):
    if (size > 1024*1024*1024.0):
        numstr = str(size/(1024*1024*1024.0))
        sizename = numstr[:(numstr.index('.')+3)]+'GB'
    elif (size > 1024*1024.0):
        numstr = str(size/(1024*1024.0))
        sizename = numstr[:(numstr.index('.')+3)]+'MB'
    elif (size > 1024.0):
        numstr = str(size/1024.0)
        sizename = numstr[:(numstr.index('.')+3)]+'KB'
        sizename = str(size) +'Bytes'
    return sizename

5. Output result (output the maximum file name, first find the address of the maximum file in the list, and then use the address to find the corresponding file name)

size = max(list_size)
s = getsizename(size)
name = list_name[list_size.index(max(list_size))]
print("C++Document has",cppnum,"individual")
print("Java Document has",javanum,"individual")
print("Python Document has",pynum,"individual")
print("Go Document has",gonum,"individual")
print("The maximum file size is",s)
print("The largest file name is",name)


Keywords: Python Java

Added by mjh513 on Sun, 09 Feb 2020 18:49:34 +0200