如果不存在定界符,则继续操作,并始终写入内容

时间:2019-06-05 19:44:03

标签: python-3.x

我有一个要打印的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

2 个答案:

答案 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])