ProvaPratica 2013.05.29
Jump to navigation
Jump to search
[Python 3]
'''
Prova Pratica di Laboratorio di Sistemi Operativi
29 maggio 2013
Esercizio 3
URL: http://www.cs.unibo.it/~renzo/so/pratiche/2013.05.29.pdf
@author: Tommaso Ognibene
'''
import os, sys
def Main(argv):
# Check number of arguments
if len(argv) != 2:
print("The function requires one argument to be passed in.")
return
# Check parameters
topDir = str(sys.argv[1])
if not os.path.isdir(topDir):
print("The parameter should be an existing directory.")
return
# Build a dictionary with key-value pair {file extension - total size}
extensionSize = { }
GetSize(topDir, extensionSize)
# Print results
PrintResults(extensionSize)
def GetSize(topDir, extensionSize):
for dirPath, dirNames, files in os.walk(topDir):
for file in files:
# 'example.mp3' -> ['example', 'mp3']
# 'example.tar.gz' -> ['example', 'tar', 'gz']
parts = file.split('.')
# ['example', 'mp3'] -> ['mp3']
# ['example', 'tar', 'gz'] -> ['tar', 'gz']
parts = parts[1:]
# ['mp3'] -> '.mp3'
# ['tar', 'gz'] -> '.tar.gz'
fileExtension = ".{0}".format(".".join(str(part) for part in parts))
# Compute the size in Bytes and update the dictionary
filePath = os.path.join(dirPath, file)
fileSize = os.path.getsize(filePath)
extensionSize[fileExtension] = extensionSize.get(fileExtension, 0) + fileSize
# Print results
def PrintResults(extensionSize):
for key, value in sorted(extensionSize.items()):
print('{0}: {1} Bytes.'.format(key, value))
if __name__ == "__main__":
sys.exit(Main(sys.argv))