Option to use existing m3u for playlist feature

OK, here’s some code.

from plexapi.myplex import MyPlexAccount
account = MyPlexAccount('username','password')
plex = account.resource('LAN1').connect()
music = plex.library.section('Music')
playlists = plex.playlists()

That is how I would open a session in Python using the Python PlexAPI for working on audio. LAN1 is the name of this particular PMS. Next, I create a function that reads the music library and creates “keys” for each entry.

def build_fkey2tr():
  global fkey2tr
  fkey2tr = {}
  for tr in music.searchTracks():
    fkey = tr.media[0].parts[0].file[29:].upper()
    if fkey in fkey2tr:
      print "fkey2tr ERROR:",fkey,"for",tr,"was",fkey2tr[fkey]
    fkey2tr[fkey] = tr
  print len(fkey2tr), "tracks."
  print "First 3:",fkey2tr.keys()[0:3]

build_fkey2tr()

I tend to use TAB for indention. I changed to two spaces here. To get the code to “look good” in the post I had to use a combination of the BLOCKQUOTE and PREFORMATTED TEXT functions. The file[29:] stuff is where I strip off the xxx as mentioned in my previous message. Quick-and-dirty, like I said. Next, well, look at the code.

z9=plex.playlist( 'z9' )

#pl = []
def updpl(plexpl,f):
#  global pl
  pl = []
  with open(f, 'r') as m3ufile:
    cnt = 0
    cntpl = 0
    for fname in m3ufile:
      cnt = cnt+1
      fkey = fname[9:-1].upper()
      if fkey in fkey2tr:
        cntpl = cntpl+1
        tr = fkey2tr[ fkey ]
        pl.append( tr )
        z9.addItems( tr )
      else:
        print "fname=",fname,"fkey=",fkey,"has no fkey2tr"
#      if cnt > 5:
#        break
    print cnt, "lines in M3U file."
    print len(pl),"(",cntpl,")", "tracks in playlist."
    print "First 3:",pl[0:3]

updpl( z9 , '\\\\...\\Playlists\\z9.m3u' )

There you have it. The fname[9:-1] is where I strip off the yyy and the trailing “\n”. Like Perl, Python converts input CRLF to LF ("\n"). So (quick-and-dirty) I just stripped off the last character.
This is all not rocket science. I’m sure you’ll figure it out. I’ll check back later to see if there are any questions.

NOTE: Obviously the pl variable is more or less not needed. You can see it’s partially commented out. However, I wonder if there’s a Plex expert out there actually reading this. If so, would it be better to build pl and then call addItems once (for all in pl), or one at a time (tr) like I’m doing now (in my first attempt — which worked!). Since it’s basically a one-time thing, it’s not all that important. But I figured I’d ask.

1 Like