4

我有一种情况,我想将 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 次,目录将在那里。

4

1 回答 1

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
于 2013-03-06T22:45:53.210 回答