Python Mutagen tag KeyError,tag不存在时如何传递

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

在 Mutagen 中,我从音频文件中读取标签,但是当标签不存在时,我当然会收到错误消息。

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

KeyError: 'TXXX:SERIES'

如果标签不存在如何继续?

我试过:

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

还有

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

还是报错

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'

你必须使用 try/except:

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

如果你希望异常发生时什么都不发生,只需使用 pass:

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

您可以在此处了解有关捕获异常/异常处理的更多信息:https://docs.python.org/3/tutorial/errors.html