pythonmutagen

Python Mutagen tag KeyError, how to pass when tag does not exists


In Mutagen i read tags form an audiofile but when the tag don't exist, i get an error of course.

audio = ID3(musicfile)
print(audio['TXXX:SERIES'].text[0])

KeyError: 'TXXX:SERIES'

how to move on if tag don't exist?

i have tried:

 if audio['TXXX:SERIES'].text[0] is None:
        print('No series')
    else:

also

if not audio['TXXX:SERIES'].text[0]:
            print('No series')
        else:

still gives an error.

Traceback (most recent call last):
  File "D:\xxxxx\all_the_program.py", line 163, in <module>
    if audio['TXXX:SERIES'].text[0] is None:
  File "D:\xxxxx\venv\lib\site-packages\mutagen\_util.py", line 537, in __getitem__
    return self.__dict[key]


Traceback (most recent call last):
  File "D:\xxxxx\all_the_program.py", line 163, in <module>
    if not audio['TXXX:SERIES'].text[0]:
  File "D:\xxxxxx\venv\lib\site-packages\mutagen\_util.py", line 537, in __getitem__
    return self.__dict[key]
KeyError: 'TXXX:SERIES'

Solution

  • You have to use try/except:

    try:
        print(audio['TXXX:SERIES'].text[0])
    except:
        print('An exception occurred')
    

    And if you want that nothing happens when an exception occurs, just use pass:

    try:
        print(audio['TXXX:SERIES'].text[0])
    except:
        pass
    

    You can learn more about catching exceptions / exceptions handling here: https://docs.python.org/3/tutorial/errors.html