Skip to content

Instantly share code, notes, and snippets.

@sethrj
Created February 10, 2014 02:31
Show Gist options
  • Save sethrj/8909395 to your computer and use it in GitHub Desktop.
Save sethrj/8909395 to your computer and use it in GitHub Desktop.
Move all music files from your itunes Library to another directory, using the "Library -> Export Playlist" data file.
###############################################################################
# File : seth/relocate_music.py
# Author: Seth R Johnson
# Date : Mon Feb 03 00:24:31 2014
###############################################################################
from __future__ import (division, absolute_import, print_function, )
#-----------------------------------------------------------------------------#
import csv
from collections import namedtuple
import logging as log
import sys
import os
###############################################################################
def translate_path_bits(macos_path):
return ['/Volumes'] + macos_path.split(':')
def translate_path(macos_path):
return os.path.join(*translate_path_bits(macos_path))
class Mover(object):
filepath = '/Volumes/Persei/Removed Music/Remove.txt'
orig_root = '/Volumes/Persei/iTunes Media/Music'
new_root = '/Volumes/Persei/Removed Music'
def __init__(self):
self.rowcls = None
self.data = []
def load(self):
with open(self.filepath, 'rU') as f:
data = f.read()
text = data.decode('utf16')
lines = text.split('\n')
f = iter(lines)
headers = next(f).split('\t')
pyheaders = [h.decode('ascii').lower().replace(" ","_")
for h in headers]
self.rowcls = rowcls = namedtuple("Row", pyheaders)
for line in f:
try:
datum = rowcls(*line.split('\t'))
except TypeError as e:
log.exception(e)
log.error("Faulty data: %s", repr(line))
self.data.append(datum)
def move(self):
for d in self.data:
if not d.location:
log.error("Bad location for %s: %s", d.name, d.location)
continue
orig_path = translate_path(d.location)
if not os.path.exists(orig_path):
log.warning("Nonexistent file: %s", orig_path)
continue
new_path = orig_path.replace(self.orig_root, self.new_root)
if new_path == orig_path:
log.error("Bad original path: %s", orig_path)
continue
(dirname, basename) = os.path.split(new_path)
if not os.path.isdir(dirname):
print("Creating directory", dirname)
os.makedirs(dirname)
print("Moving", basename)
try:
os.rename(orig_path, new_path)
except OSError as e:
log.exception(e)
log.error("Couldn't move %s to %s", orig_path, new_path)
def main():
m = Mover()
m.load()
m.move()
#-----------------------------------------------------------------------------#
if __name__ == '__main__':
main()
###############################################################################
# seth/relocate_music.py
###############################################################################
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment