Skip to content

Instantly share code, notes, and snippets.

@kelvan
Created May 16, 2018 11:41
Show Gist options
  • Save kelvan/ef45014b1f73e50c64018303973310d3 to your computer and use it in GitHub Desktop.
Save kelvan/ef45014b1f73e50c64018303973310d3 to your computer and use it in GitHub Desktop.
Copy files of xspf playlist (relative paths) to target folder, preserving folder structure
#!/usr/bin/env python3
import argparse
import os
from pathlib import Path
import shutil
import sys
from xml.dom import minidom
parser = argparse.ArgumentParser(description='Copy files of xspf playlist to target folder')
parser.add_argument('playlist')
parser.add_argument('target')
def build_folder_structure(file_path, target_folder):
# Joining with an absolute path would cause destruction
assert not file_path.is_absolute()
full_target_path = target_folder.joinpath(file_path)
assert not full_target_path.parent.exists() or full_target_path.parent.is_dir()
if not full_target_path.parent.exists():
full_target_path.parent.mkdir(parents=True, exist_ok=True)
return full_target_path
def copy_file(file_path, target_path, base_dir):
full_target_path = build_folder_structure(file_path, target_path)
# Joining with an absolute path would cause destruction
assert not file_path.is_absolute()
source_file_path = base_dir.joinpath(file_path)
if full_target_path.exists():
print('File already exist: {}'.format(full_target_path))
elif not source_file_path.exists():
print('File not found: {}'.format(source_file_path))
else:
print('Copy {0}'.format(file_path))
shutil.copy(source_file_path, full_target_path)
def copy_playlist_files(playlist, target_folder, base_dir):
with open(playlist, 'r') as f:
xspf = minidom.parse(f)
for location in xspf.getElementsByTagName('location'):
file_path = Path(location.firstChild.nodeValue)
copy_file(file_path, target_folder, base_dir)
if __name__ == '__main__':
args = parser.parse_args()
playlist = Path(args.playlist)
target_folder = Path(args.target)
if not playlist.exists():
print('Playlist not found', file=sys.stderr)
sys.exit(1)
if not target_folder.is_dir():
print('Target folder not found or not a directory', file=sys.stderr)
sys.exit(1)
base_dir = playlist.parent
copy_playlist_files(playlist, target_folder, base_dir)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment