我有一个要打印的mp3文件列表:歌手,请给下面的作品加上标题,但是,如果遇到的文件没有斜线“-”,它当然会停止,我该如何制作继续,只打印艺术家的文件名是什么?
for mp3file in glob.glob("**/*.mp3", recursive = True):
path, filename = os.path.split(mp3file)
NoExtension = os.path.splitext(filename)[0]
print('Name: '+NoExtension)
splitFilename = NoExtension.split(' - ', 1)
print('Artist: '+splitFilename[0]+'\n')
print('Title: '+splitFilename[1])
输出
Name: CamelPhat - Both [Club Remix] [Clean, Music-In, Music-Out, Mashup Redrum]
Artist: CamelPhat
Title: Both [Club Remix] [Clean, Music-In, Music-Out, Mashup Redrum]
Name: Bob Marley - Is This Love (Montmartre - Remix) [Peak Hour Redrum] [Mashup] [Clean, Beat-In, Beat-Out, Mashup]
Artist: Bob Marley
Title: Is This Love (Montmartre - Remix) [Peak Hour Redrum] [Mashup] [Clean, Beat-In, Beat-Out, Mashup]
Name: Molly (Dj Nasa Secret Bootleg)
Artist: Molly (Dj Nasa Secret Bootleg)
Traceback (most recent call last):
File "G:\Scripts\IDremoveAndReplace.py", line 20, in <module>
print('Title: '+splitFilename[1])
IndexError: list index out of range
答案 0 :(得分:0)
您可以尝试将代码-阻止,并让异常打印您想要的内容
例如
for mp3file in glob.glob("**/*.mp3", recursive = True):
try:
path, filename = os.path.split(mp3file)
NoExtension = os.path.splitext(filename)[0]
print('Name: '+NoExtension)
splitFilename = NoExtension.split(' - ', 1)
print('Artist: '+splitFilename[0]+'\n')
print('Title: '+splitFilename[1])
except IndexError as e:
print(e)
#Some other logic here
print('Cannot find title')
答案 1 :(得分:0)
一种选择是使用try块:
for mp3file in glob.glob("**/*.mp3", recursive = True):
path, filename = os.path.split(mp3file)
NoExtension = os.path.splitext(filename)[0]
print('Name: ' + NoExtension)
splitFilename = NoExtension.split(' - ', 1)
print('Artist: ' + splitFilename[0] + '\n')
try:
print('Title: ' + splitFilename[1])
except IndexError as ie:
print('Title: ' + splitFilename[0])