[英]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. 我试图将路径下的不同文件夹中的文件复制到我的USB驱动器。 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 Songs_1 Songs_2 Songs_3
the target folder is under anyone of these Songs directory 目标文件夹位于这些Songs目录中的任何一个目录下
Songs_1/Kid Rock/All summer long.mp3 Songs_1 / Kid Rock /整个夏天很长.mp3
Songs_2/Linkin Park/In the end.mp3 歌曲_2 /林肯公园/最后.mp3
Now I am constructing my src_dir in a try/except way like this. 现在我正在尝试使用这样的try / except方法构建我的src_dir。
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 ? 有一个更好的方法吗 ?
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... 而且,如果您成功将源复制到目标,也许您想要添加break
语句...
As a side note, you might want to use os.path.join
instead: 作为旁注,您可能希望使用os.path.join
:
src_dir_1 = os.path.join(src_dir, sdir, album, s + ".mp3")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.