使用目录|蟒蛇

时间:2013-01-06 03:57:23

标签: python directory organization

我正在编写代码来整理+ 40G的音乐,现在所有文件都在一个大文件夹中,我的目标是为每个艺术家创建一个目录。现在,我已经能够提取艺术家信息,并用它创建一个目录,但我发现的一个问题是,如果我有两个具有相同艺术家信息的文件,我会得到两个文件夹的错误同名。

我需要帮助防止第二个文件夹发生。

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

1 个答案:

答案 0 :(得分:2)

在try / except中包装mkdir并捕获目录存在时引发的异常。确保还导入errno模块。

try:
    os.mkdir(os.path.expanduser('~/Desktop/mp3-organizer/%s' % song_info.tag.artist))
except OSError as e:
    if e.errno != errno.EEXIST:
        raise

您还可以使用os.path.isdir()检查目录是否存在,但这会引入竞争条件。