Reputation: 67
i'm writing code to organize +40G's of music, right now all the files are in one big folder, my goal is to have a directory for each artist. right now, i've been able to extract the artist info, and make a directory with it, but an issue that i've found is that if i have two files with the same artist info, i am given the error of two folders with the same name.
I need help with preventing the second folder from happening.
import os #imports os functions
import eyed3 #imports eyed3 functions
root_folder = '/Users/ntoscano/desktop/mp3-organizer'
files = os.listdir(root_folder) #lists all files in specified directory
if not files[1].endswith('.mp3'):
pass #if the file does not end with ".mp3" it does not load it into eyed3
for file_name in files:
if file_name.endswith('.mp3'): #if file ends with ".mp3" it continues onto the next line
abs_location = '%s/%s' % (root_folder, file_name)
song_info = eyed3.load(abs_location) #loads each file into eyed3 and assignes the return value to song_info
if song_info is None:
print 'Skippig %s' % abs_location
continue
os.mkdir(os.path.expanduser('~/Desktop/mp3-organizer/%s' % song_info.tag.artist))
print song_info
print song_info.tag.artist
else:
pass
Upvotes: 1
Views: 130
Reputation: 12174
Wrap the mkdir
in a try/except and catch the exception raised when the directory exists. Make sure to also import the errno
module.
try:
os.mkdir(os.path.expanduser('~/Desktop/mp3-organizer/%s' % song_info.tag.artist))
except OSError as e:
if e.errno != errno.EEXIST:
raise
You could also check if the directory exists using os.path.isdir()
, but this introduces a race condition.
Upvotes: 2