In: Computer Science
Create a script that take a directory path from the user. What I want you to do is figure out the total size of all files in the directory. You will need to import the os module for this.
BELOW IS THE SOLUTION TO YOUR PROBLEM:
import os
path=input("Please enter path: ")
dirs = os.listdir(path) #it will return list of names of files in
given directory
noOffiles=int(0) #counting number of files
totalSize=int(0) #for calculation of total size of file
for file in dirs: #looping through dirs
print(file) #printing files in directory
for file in dirs:
if os.path.isfile(file): #checking if given file name
is existing file
totalSize+=os.path.getsize(file) #calculating file size
and adding it in totalSize
noOffiles+=1 #counting number of
files
if(totalSize>1024): # as mentioned in reqirment if size is
more than 1024 then convert it in kb
inKB=totalSize/1024
print("Total size: {0:.2f} KB".format(inKB))
else:
print("Total size: "+str(totalSize)+" bytes");
avg=totalSize/noOffiles #calculation avg file size
if(avg>1024):
inKB=avg/1024
print("Average size of file: {0:.2f}
KB".format(inKB))
else:
print("Average size: "+str(avg)+" bytes");
Picture of code:
OUTPUT:
IF YOU HAVE ANY QUERY PLEASE COMMENT DOWN BELOW.
PLEASE GIVE A THUMBS UP