0

I am trying to select a random music file from a folder in Python using the windows commands: random.choice() os.listdir() os.startfile()

Here is the code:

import os, random song = random.choice(os.listdir("C:\Users\MASONF\Music\Downloaded")) os.startfile(song)

It returns the error

Traceback (most recent call last): File "C:\Users\MASONF\Desktop\successfuly chosen random file non existent.py", line 3, in <module> os.startfile(song) WindowsError: [Error 2] The system cannot find the file specified: 'Panda Eyes - Drippy Dub.mp3'

The file exists but it can't find it? I am new to Python and don't know many commands for anything so I have probably missed something obvious

333
  • 13
  • 2

1 Answers1

0

You will need add the base path to the song name:

import os, random
path = r"C:\Users\MASONF\Music\Downloaded"
song = random.choice(os.listdir(path))
os.startfile(path+'\\'+song)
Alex Fung
  • 1,996
  • 13
  • 21