目录不存在时的错误处理

时间:2013-03-06 22:31:26

标签: python

我有一种情况,我想将MP3存储在一个目录中,如果该目录不存在则创建该目录,如果无法创建该目录,则退出该程序。我读到os.path.exists()涉及的性能比os.makedirs()更受欢迎,所以考虑到这一点,我精心设计了以下代码:

try: 
    # If directory has not yet been created
    os.makedirs('Tracks')
    with open('Tracks/' + title + '.mp3', 'w') as mp3:
        mp3.write(mp3File.content)
        print '%s has been created.' % fileName

except OSError, e:
    # If directory has already been created and is accessible
    if os.path.exists('Tracks'):
        with open('Tracks/' + title + '.mp3', 'w') as mp3:
            mp3.write(mp3File.content)
            print '%s has been created.' % fileName

    else: # Directory cannot be created because of file permissions, etc. 
        sys.exit("Error creating 'Tracks' Directory. Cannot save MP3. Check permissions.")

这有意义吗?或者我应该坚持使用更干净但可能更昂贵的版本,只需检查目录是否先存在然后制作它? 9/10次,目录将在那里。

1 个答案:

答案 0 :(得分:2)

try-except块可能更快,但正如@ t-8ch所说,它并不重要。但是,它不一定是'不洁净':

try: 
    # try the thing you expect to work
    mp3 = open('Tracks/' + title + '.mp3', 'w')
except OSError, e:
    # exception is for the unlikely case
    os.makedirs('Tracks')
    mp3 = open('Tracks/' + title + '.mp3', 'w')

mp3.write(mp3File.content)
mp3.close()
print '%s has been created.' % fileName

如果您希望try首先制作目录,可以执行以下操作:

try: 
    # If directory has not yet been created
    os.makedirs('Tracks')
except OSError, e:
    # If directory has already been created or is inaccessible
    if not os.path.exists('Tracks')
        sys.exit("Error creating 'Tracks' Directory. Cannot save MP3. Check permissions.")
with open('Tracks/' + title + '.mp3', 'w') as mp3:
    mp3.write(mp3File.content)
    print '%s has been created.' % fileName