-1

I am trying to open a random mp3 file using python so that I can play a random song from my music playlist.

these are two variations of the code that I have tried

file = str('C:\file.mp3')
open(file)

or

open('C:\file.mp3')

When I run the program, I expect to see the Microsoft mp3 player to open and for the file to play but instead I get a pop-up message saying "Unicode error: 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape".

I have never used open() before so if it is something very simple then I'm sorry.

David Brossard
  • 13,584
  • 6
  • 55
  • 88
  • 1
    "I expect to see the Microsoft mp3 player to open" why? Also, documentation -> https://docs.python.org/3/library/functions.html#open – njzk2 Jul 09 '19 at 03:23
  • on some systems you can use `import webbrowser`; `webbrowser.open(filename)` to open this file with default program in system. If you need to open in different program then you may need `os.system("your_player.exe your_file.mp3")` – furas Jul 09 '19 at 03:30

2 Answers2

4

Always use raw strings for Windows file paths (and regexes). Otherwise, a folder whose name begins with U (say, C:\Users) ends up looking like the beginning of a Unicode escape; many other characters end up being interpreted as escapes as well (e.g. f is escaped to the form feed character).

Using raw strings (prefixed with r) means backslashes only escape the quote character, nothing else. So:

with open(r'C:\file.mp3') as f:

works, where:

with open('C:\file.mp3') as f:

wouldn't. That said, none of this would open the file in your music player. open opens the raw file to read data from it (odds are an mp3 file will error if you try to read it in text mode, unless you're using one of the more permissive codecs, like latin-1). If you want to launch a file via its default handler, that's what os.startfile is for, e.g.:

os.startfile(r'C:\file.mp3')
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
1

This question has been asked before. A link to the documentation can be found here

Please see Can Python Open a MP3 File.

You can use the built in os library:

import os
os.startfile('my_mp3.mp3')
adlopez15
  • 3,449
  • 2
  • 14
  • 19