简体   繁体   English

Python Mutagen tag KeyError, tag不存在时如何通过

[英]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.在 Mutagen 中,我从音频文件中读取标签,但是当标签不存在时,我当然会收到错误消息。

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'

You have to use try/except:你必须使用 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:如果您希望在发生异常时不发生任何事情,只需使用 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您可以在此处了解有关捕获异常/异常处理的更多信息: https://docs.python.org/3/tutorial/errors.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM