Arun Raman
Arun Raman

Reputation: 15

Need to implement nested try statements with one exception

I am trying to copy a files from different folders under a path to my usb drive. So my source directory structure looks like this

/user/arun/Music/Songs/

under this I have different sub directories

Songs_1 Songs_2 Songs_3

the target folder is under anyone of these Songs directory

Songs_1/Kid Rock/All summer long.mp3
Songs_2/Linkin Park/In the end.mp3

Now I am constructing my src_dir in a try/except way like this.

for album,song in song_database.iteritems():
    for s in song:
        try:
            src_dir_1 = src_dir + "/" + "Songs_1" + "/" + album + "/" + s + ".mp3"
            shutil.copy2(src_dir_1,dest_dir
            print src_dir_1
        except IOError:
            pass
        try:
            src_dir_1 = src_dir + "/" + "Songs_2" + "/" + album + "/" + s + ".mp3"
            shutil.copy2(src_dir_1,dest_dir)
            print src_dir_1
        except IOError:
            pass
        try:
            src_dir_1 = src_dir + "/" + "Songs_3" + "/" + album + "/" + s + ".mp3"
            shutil.copy2(src_dir_1,dest_dir)
            print src_dir_1
        except IOError:
            pass
        try:
            src_dir_1 = src_dir + "/" + "Songs_4" + "/" + album + "/" + s + ".mp3"
            shutil.copy2(src_dir_1,dest_dir)
            print src_dir_1
        except IOError:
            pass

Is there a better way to do this ?

Upvotes: 0

Views: 54

Answers (1)

mgilson
mgilson

Reputation: 309891

Seems like a loop would be better:

for album,song in song_database.iteritems():
    for s in song:
        for sdir in 'Songs_1', 'Songs_2', 'Songs_3':
            try:
                src_dir_1 = src_dir + "/" + sdir + "/" + album + "/" + s + ".mp3"
                shutil.copy2(src_dir_1,dest_dir)
                print src_dir_1
            except IOError:
                pass

And, perhaps you would want to add a break statement if you succeed in copying the source to the destination...

As a side note, you might want to use os.path.join instead:

src_dir_1 = os.path.join(src_dir, sdir, album, s + ".mp3")

Upvotes: 2

Related Questions