LIST FILES AND FOLDERS WITH THEIR RESPECTIVE SIZES
Here is a python script which prints list of files and folders with their respective sizes. This script is particularly useful on Windows systems. Create a file with .py extension and paste the below code in the file. Copy the file to any directory or drive and run it on command prompt.
#to list files and directories with size in the current path
import os #importing the module os
from columnar import columnar #to create a table on output, install it with: pip install columnar
filepath = '.' #setting the path for which files and directories are to be seen
file_list = os.listdir(filepath) #getting the list of files and directories
data = [] #in this list/array, we shall add each file/folder name with their respective sizes(in KB/MB/GB)
sizes = [] #in this list/array, add all the sizes
for x in file_list:
file_size = os.path.getsize(filepath+"/"+x) #calculating size of each file item
file_size = file_size / 1024
file_size = round(file_size, 2)
if file_size > 1000:
file_size = file_size / 1024
file_size = round(file_size,1)
size_as = str(file_size)+'MB'
sizes += [size_as] #adding the sizes in MB to the list
elif file_size > 1024:
file_size = file_size / 1024
file_size = round(file_size,1)
size_as = str(file_size)+'GB' #adding the sizes in GB to the list
sizes += [size_as]
else:
size_as = str(file_size)+'KB' #adding the sizes in KB to the list
sizes += [size_as]
ziplist = zip(file_list, sizes) #combining the list of files/directories with list of sizes
for x, y in ziplist:
data.append([x, y]) #creating a list of file item and corresponding size value
and appending all the lists to the main list data
headers = ['Name', 'Size'] #create the table headings
table = columnar(data, headers) #generate the entire table
print(table) #now print the data for display
Comments
Post a Comment