iTunes Library Parser – iTunesParser

class iTunesParser:
'''Class for parsing an iTunes Library'''

def __init__(self, input_file):
    '''Constructor'''
    self.source = input_file #Source file
    self.xml = ElementTree.parse(input_file) # Parsed XML File in a tree
    self.library = list() #List containing all the tracks


def parse(self):
    '''Parse the file'''
    # Documentation about Element Tree ->  http://docs.python.org/2/library/xml.etree.elementtree.html
    root = self.xml.getroot()
    
    #Find index of element containing tracks
    i = 0
    
    for child in root[0]:
        if child.text == "Tracks":
            tracksIndex = i+1
            break
        i += 1
    
            
    #Loop trough all songs
    i = 0
    for song in root[0][tracksIndex]:
        #Every second element is a track
        if i % 2 == 1:
            
            #Loop through metadata of the track and extract info
            j = 0
            
            albumArtist = None
            
            for tag in song:

                if tag.text == "Name":
                    trackName = song[j+1].text
                
                elif tag.text == "Artist":
                    artist = song[j+1].text
                    
                elif tag.text == "Album Artist":
                    albumArtist = song[j+1].text
                    
                elif tag.text == "Album":
                    album = song[j+1].text
                    
                elif tag.text == "Genre":
                    genre = song[j+1].text
                    
                elif tag.text == "Year":
                    year = song[j+1].text
                
                j += 1
            
            
            #Sometime Album Artist is not defined, then we take the artist as album artist
            if albumArtist == None:
                albumArtist = artist
            
            #Make new track
            try:
                track = Track(trackName, artist, albumArtist, album, year, genre)
            except:
                #Sometime Album Artist is not defined, then we take the artist as album artist
                track = Track(trackName, artist, artist, album, year, genre)
            
            #Add track to 'library'
            self.library.append(track)
        
        i += 1			
        
    
    return


def getTrackList(self):
    '''Returns list with all tracks'''
    return self.library
    

def __str__(self):
    '''Returns string of iTunes Library with all albums'''
    
    string = ""
    
    for i in range ( len(self.library) ):
        
        string += str(i+1)+". "
        
        string += str(self.library[i])
        
        if i != len(self.library) - 1:
            string += "\n"
    
    return string