2

This gets the latest mp3 file in my Directory

new_file = [(os.path.getmtime(ft) , os.path.basename(ft))
            for ft in os.listdir(path) if ft.lower().endswith('.mp3')]

new_file.sort()

Assigning the latest file to the file I am going to play

playFile = new_file[0][1]

Getting the Directory for the file.

PlayfileDir = os.getcwd() + '\\' + str(playFile)

Playing the file. This is where I get the error 'PlayfileDir' cannot be found.

os.system('start "PlayfileDir"')
Luca Jeevanjee
  • 227
  • 1
  • 5
  • 12

2 Answers2

1

Since PlayfileDir is a variable that is a string, you can just concatenate it to 'start' (as pointed out by @cdarke, you need to also add the quotes!). As you have it at the moment, you are trying to start the actual string 'PlayfileDir', not the string in the variable.

So, you should do something like:

os.system('start "' + PlayfileDir + '"')
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
0

This is a great opportunity to start using pathlib!

from pathlib import Path

p = input("Gimme a path: ")

newest_mp3 = sorted(Path(p).glob('*.mp3'), reverse=True, key=lambda p: p.stat().st_mtime)[0]

os.system('start "{}"'.format(newest_mp3))
aghast
  • 14,785
  • 3
  • 24
  • 56
  • Hi this works well but it opens a command window in which i have to type the file name to play it. Is there a way to do this automatically – Luca Jeevanjee Dec 30 '17 at 13:10
  • Instead of doing `os.system(...)`, do a `print(...)` and see what is being generated. – aghast Dec 30 '17 at 17:29