Why can't I use a filename containing a space with playsound in python?

198 Views Asked by At

If I use a music file name sample.mp3, it works, but if I use sample one.mp3, it doesn't work. Even if I insert a desktop pathway, it stops working, and if I save the same file in other folders and insert its pathway, it starts working.

from playsound import playsound
playsound('play me.mp3')
1

There are 1 best solutions below

2
smcrowley On

spaces in filenames aren't supported on playsound. instead, format the string path to replace spaces like so

from playsound import playsound
path_to_play = "play me.mp3"
path_to_play = path_to_play.replace(" ", "%20")
playsound(path_to_play)

solution from https://github.com/TaylorSMarks/playsound/issues/40#issuecomment-674285344

spaces in file names is recommended to be avoided, so it might be better just to rename those files to use underscores instead of spaces

import os
for filename in os.listdir("."):
    if filename.endswith(".mp3"):
        os.rename(filename, filename.replace(" ", "_"))