“Want to write shorter, cleaner code? Have an unfortunate situation where you need to fit as much as you can in one expression? Prefer a quick dose of hacks to spending the rest of your life reading the docs? You’ve come to the right place. We start out with some quick tricks that you might have figured out if you’ve spent some time with Python, but I promise there’s more crazy stuff towards the bottom.”—
I wanted to verify that all of my songs in my iTunes library existed on my local filesystem, and vice versa, so I turned to python to help me out. I exported the entire Music library from iTunes as an “m3u” playlist called “Music.m3u”, then used python to compare and contrast. Code below:
# -*- mode: Python; tab-width: 4; indent-tabs-mode: nil; -*-
# ex: set tabstop=4 softtabstop=1 shiftwidth=4 expandtab:
# Please do not change the two lines above. See PEP 8, PEP 263.
library_path = '~/Music/iTunes/iTunes Music/'
library_path = os.path.expanduser(library_path)
m3u_songs_file = open('Music.m3u')
m3u_songs = m3u_songs_file.readline().split('\r')
m3u_songs = [song for song in m3u_songs if '#EXT' not in song]
m3u_songs = [song for song in m3u_songs if song != '']
local_filter = ['/.DS_Store', '/.iTunes Preferences.plist',
'/Mobile Applications', '/Ringtones']
local_songs = 
for root, dirs, files in os.walk(library_path):
for file in files:
songpath = os.path.join(root, file)
skip = False
for filterstr in local_filter:
if filterstr in songpath:
skip = True
if not skip:
missing_from_local = [song for song in m3u_songs if song not in local_songs]
missing_from_m3u = [song for song in local_songs if song not in m3u_songs]
print "songs in iTunes but not found on local filesystem:"
if not missing_from_local:
for song in missing_from_local:
print "\t", song
print "songs in the local filesystem but not in iTunes:"
if not missing_from_m3u:
for song in missing_from_m3u:
print "\t", song