In: Computer Science
my_list = {} Dictionary holding all the lists. s_files = [] # Files with size UNDER 50 KB. m_files = [] # Files with size AT LEAST 50 KB and UNDER 5 MB . l_files = [] # Files with size AT LEAST 5 MB, no upper limit. directories = [] # Directories, regardless of size. Write a program using python that loops over each file in a specified directory and checks the size of each file.Create 2-tuple with the filename and size, should append the 2-tuple to a list, and then store all the lists in a dictionary according to the size
import os
my_list = {} #Dictionary holding all the lists.
s_files = [] # Files with size UNDER 50 KB.
m_files = [] # Files with size AT LEAST 50 KB and UNDER 5 MB
l_files = [] # Files with size AT LEAST 5 MB, no upper limit.
directories = [] # Directories, regardless of size.
# enter the path of your directory here
directory = r'E:\test'
Unit = ["Byte","KB","MB","GB","TB"]
for filename in os.listdir(directory):
c = 0
# this will get the file size in bytes
b = os.path.getsize(os.path.join(directory, filename))
# this will convert bytes to MB.... GB... etc
while b > 1024:
b = b/1024
c+=1
size = "{:.1f}".format(b)+ " " + Unit[c]
tup = (filename,size)
# to check print output of each tuple
print(tup)
directories.append(tup)
if Unit[c]=="Byte" or Unit[c]=="KB" and b<50 :
s_files.append(tup)
elif (Unit[c]=="KB" and b>=50) or (Unit[c]=="MB" and b<5) :
m_files.append(tup)
else:
l_files.append(tup)
my_list["under 50 KB"]= s_files
my_list["between 50 KB and 5 MB"]= m_files
my_list["above 5 MB"]= l_files
This code will work for the above program
Hope this helpful
Please please please upvote as it will helps me alot
please dont downvote