目录不存在时的错误处理
我遇到一个情况,我想把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成的概率。
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