使用目录| python

使用目录| python,python,directory,organization,Python,Directory,Organization,我正在编写代码来组织+40G的音乐,现在所有的文件都在一个大文件夹中,我的目标是为每个艺术家建立一个目录。现在,我已经能够提取艺术家信息,并用它创建一个目录,但我发现的一个问题是,如果我有两个具有相同艺术家信息的文件,我会遇到两个同名文件夹的错误 我需要帮助以防止发生第二个文件夹 import os #imports os functions import eyed3 #imports eyed3 functions root_folder = '/Users/ntoscano/desktop

我正在编写代码来组织+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

在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()
检查目录是否存在,但这会引入竞争条件。

您的
如果不是文件[1]。endswith('.mp3')
行没有任何作用,仅供参考。