Search code examples
pythonglobpydub

Wildcard filenames and Pydub


Can anyone explain to me how to fix this code. If I set song equal to the full file path my script runs without any problems. However, problem is I don't always know the name of the .mp3 file in that path, so I need to point to the file as a wildcard.

from pydub import AudioSegment
import glob

my_song = glob.glob('/Users/usename/Google Drive/Developer/Voicemails/?.mp3')

song = AudioSegment.from_mp3(my_song)

song.export("/Users/username/Google Drive/Developer/Voicemails/voicemail1.flac", format="flac")

Any pointers would be awesome!


Solution

  • To get all MP3 files just replace the '?' with '*' in the path now when you use glob it will return a list of files so you will have to loop over all the files and do your stuff, (even if there is only one file in that directory).

    for example something like this:

    from pydub import AudioSegment
    import glob,os
    
    
    songs = glob.glob('/Users/usename/Google Drive/Developer/Voicemails/*.mp3')
    for my_song in songs:
        song = AudioSegment.from_mp3(my_song)
        song.export(os.path.join ("/Users/username/Google Drive/Developer/Voicemails", os.path.basename(my_song) + ".flac"), format="flac")
    

    good luck