Skip to content

Instantly share code, notes, and snippets.

@dupleix
Created July 4, 2010 18:38
Show Gist options
  • Save dupleix/463649 to your computer and use it in GitHub Desktop.
Save dupleix/463649 to your computer and use it in GitHub Desktop.
Synchronize podcasts from iTunes to an mp3 player
#!/usr/bin/env python
from appscript import *
import re, os
from pprint import pprint
from shutil import copy
PODCAST_PLIST = u'Podcasts'
DEST_PODCASTS = '/Volumes/WALKMAN/PODCASTS'
MAX_SIZE = 2*1024*1024*1024
iTunes = app('iTunes')
podcastPlaylist = None
for p in iTunes.playlists():
if p.name()==PODCAST_PLIST:
podcastPlaylist = p
break
files = [(f.album(), f.location().path, os.path.join(DEST_PODCASTS, f.album(), os.path.basename(f.location().path)), f.size(), f.date_added()) for f in podcastPlaylist.file_tracks()]
files.sort(key=lambda x: x[4], reverse=True)
podcastsToCopy = []
size=0
for f in files:
size += f[3]
if size < MAX_SIZE:
podcastsToCopy.append(f)
else: break
#List music files in the mp3 player and delete files not selected
toBeCopied = [f[2] for f in podcastsToCopy]
toBeDeleted = []
for root, dirs, files in os.walk(DEST_PODCASTS):
for f in files:
if unicode(os.path.join(root, f), 'utf-8') not in toBeCopied:
toBeDeleted.append(os.path.join(root, f))
print len(toBeDeleted), "files to be deleted..."
i=0
for f in toBeDeleted:
try:
os.remove(f)
except:
pass
i=i+1
print i, '/', len(toBeDeleted), f
#delete empty directories
os.popen("find %s -type d -empty -delete" % DEST_PODCASTS)
#Copy podcasts
print len(podcastsToCopy), "files to be copied..."
i=0
for f in podcastsToCopy:
print i, '/', len(podcastsToCopy), f[0]
if not os.path.exists(f[2]):
if not os.path.exists(os.path.dirname(f[2])):
os.makedirs(os.path.dirname(f[2]))
copy(f[1], os.path.dirname(f[2]))
i = i+1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment