Home > Blockchain >  Second parse returns empty but first returns full
Second parse returns empty but first returns full

Time:08-21

I am parsing a .xml file from Apple Music, and pulling the names, artists, and albums from each song in a playlist. If I run the program, only calling one function, it returns as expected.

If I run the program with more than one function called, it returns the first call as expected and the other as empty.

With one function

    import xml.etree.ElementTree as ET
    tree = ET.parse('Rock.xml')
    root = tree.getroot
    tags = root().iter()
    def find_name():
        key = 'Name'
        songs = []
        for elem in tags:
            if key == elem.text:
                next_elem = next(tags)
                songs.append(next_elem.text)
        del songs[-1]
        return songs
    
    def find_artist():
        key = 'Artist'
        artists = []
        for elem in tags:
            if key == elem.text:
                next_elem = next(tags)
                artists.append(next_elem.text)
        return artists
    
    def find_album():
        key = 'Album'
        albums = []
        for elem in tags:
            if key == elem.text:
                next_elem = next(tags)
                albums.append(next_elem.text)
        return albums

One function result (expected)

["(Don't Fear) The Reaper", 'Let It Be', 'Hot Blooded', 'Tom Sawyer', 'Limelight', 'YYZ', 'Seven Cities of Gold', 'Highway to Hell', "Sweet Child O' Mine", 'Wheel In the Sky', 'Smoke On the Water', "Don't Stop Believin'", 'Back In Black', 'American Idiot', 'Another Brick In the Wall, Pt. 3', 'Iron Man', 'Godzilla', "Livin' On a Prayer", 'No One Knows', 'Thunderstruck', 'All the Small Things', 'Cult of Personality', 'Holiday', 'Basket Case', 'Boulevard of Broken Dreams', 'You Give Love a Bad Name', 'Heading Out to the Highway']

Both functions called (Album called first, then names)

['Blue Öyster Cult', 'The Beatles', 'Foreigner', 'Rush', 'Rush', 'Rush', 'Rush', 'AC/DC', "Guns N' Roses", 'Journey', 'Deep Purple', 'Journey', 'AC/DC', 'Green Day', 'Pink Floyd', 'Black Sabbath', 'Blue Öyster Cult', 'Bon Jovi', 'Queens of the Stone Age', 'AC/DC', 'blink-182', 'Living Colour', 'Green Day', 'Green Day', 'Green Day', 'Bon Jovi', 'Judas Priest']
    Traceback (most recent call last):
      File "c:\Users\lucap\Documents\Development\Moving-Music\applemusic_xl.py", line 37, in <module>
        print(find_name())
      File "c:\Users\lucap\Documents\Development\Moving-Music\applemusic_xl.py", line 14, in find_name
        del songs[-1]
    IndexError: list assignment index out of range

The list returns empty, and thus throws this error at me.

CodePudding user response:

I need to call

tags = root().iter() 

after each successful parse.

I'm not entirely sure why this is the case, but that did fix my issue.

  • Related