Home > Software engineering >  Python program unable to access sound (and other files) from subdirectories
Python program unable to access sound (and other files) from subdirectories

Time:12-03

I have a few functions in my program to print from text files, and to play sound files using Path. One such function allows me to run the program from ANY directory, and it can still find and play its sound files. It works perfectly, except in only plays files located in the program directory:

def sound_player_loop(sound_file):
    # a sound player function which plays sound_file asynchronously on a continuous loop
    try:
        
        p = Path(__file__).with_name(sound_file)
        with p.open('rb') as sound:
            
    if sound.readable():
                winsound.PlaySound(str(p), winsound.SND_FILENAME | winsound.SND_LOOP | winsound.SND_ASYNC)
    
    except FileNotFoundError:
        print(f"{sound_file} not found in directory path.")
        pause()
           

I simply want to be able to move my sound files to a sound\ subdirectory within the program directory and have the same functionality, but I am having trouble with Path.

app_dir\
|
|-----sound\

I have tried

sound_folder = Path("sound/")
file_to_play = sound_folder / sound_file
p = Path(__file__).with_name(file_to_play)

and a few other variations..

Which results in: TypeError: Path.replace() takes 2 positional arguments but 3 were given... Current functionality is fine, except I just want to tidy up the program directory and move all sounds and eventually all externally printed text files to subdirectories. I am currently using Windows, but would like it to work on *nix as well.

CodePudding user response:

To resolve relative to the directory of __file__ you need something like

sound_folder = Path(__file__).with_name("sound")
...
p = sound_folder / sound_file
  • Related