0

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 ?

1
  • Why would you want to ignore an IOError? Commented Dec 13, 2013 at 2:21

1 Answer 1

2

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")
Sign up to request clarification or add additional context in comments.

1 Comment

When I see people not using the os.path package I cringe a bit

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.