« Plug-in cars | Main | At the library »

August 15, 2005

Random playlist

I'm playing around with my MP3 reader and python. Python's a good language for handling lists and dictionaries and so forth, but I don't know it yet. So it took me some time to figure out where the pieces were for a short program that generates a random playlist of the size that fits onto my MP3 reader.

import glob
import os.path
import random
import shutil

MUSIC_SRC = "/home/mark/music/*/*/*.[mw][pm][3a]"
MAX_SIZE = 516538368L # Available blocks on my MP3 player when empty
MUSIC_DST = "/media/usbdisk/"

files = glob.glob(MUSIC_SRC)

list = {}
for filename in files:
list[filename] = os.path.getsize(filename)

playlist = []
totalsize = 0
maxsize = MAX_SIZE
while files:
song = random.choice(files)
files.remove(song)
totalsize += list[song]
if maxsize > totalsize:
playlist.append(song)

number = 1
for song in playlist:
copyname = MUSIC_DST + str(number).zfill(3) + " - " + os.path.basename(song)
shutil.copyfile(song, copyname)
number = number + 1

I've had one problem with this:

Traceback (most recent call last):
  File "playlist.py", line 29, in ?
    shutil.copyfile(song, copyname)
  File "/usr/lib/python2.4/shutil.py", line 48, in copyfile
    fdst = open(dst, 'wb')
IOError: invalid mode: wb

Huh? Forget it. I'm going to bed.

Posted by Mark at August 15, 2005 10:58 PM