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