ProvaPratica 2013.05.29

From Sistemi Operativi
Revision as of 19:07, 21 November 2013 by TomOgn (talk | contribs) (Created page with "[Python 3] <syntaxhighlight lang="Python"> ''' Prova Pratica di Laboratorio di Sistemi Operativi 29 maggio 2013 Esercizio 3 URL: http://www.cs.unibo.it/~renzo/so/pratiche/20...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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))