user1427661
user1427661

Reputation: 11774

Error Handling for When a Directory Doesn't Exist

I have a situation where I want to store MP3s in a directory, create that directory if it doesn't exist, and exit the program if the directory cannot be created. I read that os.path.exists() involves more of a hit to performance than os.makedirs(), so with that in mind I crafted the following code:

try: 
    # If directory has not yet been created
    os.makedirs('Tracks')
    with open('Tracks/' + title + '.mp3', 'w') as mp3:
        mp3.write(mp3File.content)
        print '%s has been created.' % fileName

except OSError, e:
    # If directory has already been created and is accessible
    if os.path.exists('Tracks'):
        with open('Tracks/' + title + '.mp3', 'w') as mp3:
            mp3.write(mp3File.content)
            print '%s has been created.' % fileName

    else: # Directory cannot be created because of file permissions, etc. 
        sys.exit("Error creating 'Tracks' Directory. Cannot save MP3. Check permissions.")

Does this make sense? Or should I stick with the cleaner but perhaps costlier version of simply checking whether the directory exists first and then making it? 9/10 times, the directory is going to be there.

Upvotes: 5

Views: 17694

Answers (1)

askewchan
askewchan

Reputation: 46530

Thetry-except block probably is faster, though as @t-8ch says, it doesn't really matter. However, it doesn't have to be so 'unclean':

try: 
    # try the thing you expect to work
    mp3 = open('Tracks/' + title + '.mp3', 'w')
except OSError, e:
    # exception is for the unlikely case
    os.makedirs('Tracks')
    mp3 = open('Tracks/' + title + '.mp3', 'w')

mp3.write(mp3File.content)
mp3.close()
print '%s has been created.' % fileName

If you do want to try to make the directory first, you can do:

try: 
    # If directory has not yet been created
    os.makedirs('Tracks')
except OSError, e:
    # If directory has already been created or is inaccessible
    if not os.path.exists('Tracks')
        sys.exit("Error creating 'Tracks' Directory. Cannot save MP3. Check permissions.")
with open('Tracks/' + title + '.mp3', 'w') as mp3:
    mp3.write(mp3File.content)
    print '%s has been created.' % fileName

Upvotes: 2

Related Questions