我有一种情况,我想将 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.")
Run Code Online (Sandbox Code Playgroud)
这有道理吗?或者我应该坚持使用更干净但可能更昂贵的版本,即首先检查目录是否存在然后创建它?9/10次,目录就会在那里。
该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
Run Code Online (Sandbox Code Playgroud)
如果你确实想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
Run Code Online (Sandbox Code Playgroud)