Skip to content

Instantly share code, notes, and snippets.

@galvez
Created February 2, 2009 20:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save galvez/57084 to your computer and use it in GitHub Desktop.
Save galvez/57084 to your computer and use it in GitHub Desktop.
import re, os
path = r'C:\Home\OldMusic'
def get_files_out_of_subdirs(path):
base_level_len = len(path.split(os.path.sep))
for n, d, files in os.walk(path):
n = n.split(os.path.sep)
top_level = (len(n) == base_level_len+1)
if top_level: top_level_dir = n
if not top_level:
for file in files:
if re.search('(?i)\.(?:mp3|m4a)$', file):
old_path = os.path.sep.join(n + [file])
new_path = os.path.sep.join(top_level_dir + [file])
try:
os.rename(old_path, new_path)
except Exception, e: # filename conflict, write like 'filename (2).mp3'
if 'Error 183' in str(e):
filename, ext = os.path.splitext(file)
version = 2
new_path = os.path.sep.join(top_level_dir + ['%s (%s)%s' % (filename, version, ext)])
path_exists = os.path.exists(new_path)
while path_exists:
version += 1
new_path = os.path.sep.join(top_level_dir + ['%s (%s)%s' % (filename, version, ext)])
path_exists = os.path.exists(new_path)
os.rename(old_path, new_path)
print new_path
ls = os.listdir(os.path.sep.join(n))
if len(ls) == 0:
os.rmdir(os.path.sep.join(n))
def put_artist_name_on_files(path):
base_level_len = len(path.split(os.path.sep))
for n, d, files in os.walk(path):
n = n.split(os.path.sep)
if len(n) > base_level_len-1:
artist_name = n[base_level_len]
for file in files:
if re.search('(?i)\.(?:mp3|m4a)$', file):
if not file.lower().startswith(artist_name.lower()):
old_path = os.path.sep.join(n + [file])
new_path = os.path.sep.join(n + ['%s - %s' % (artist_name, file)])
os.rename(old_path, new_path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment