Python 2.6文件存在错误号17,
如果文件已经存在,我如何消除错误17并发出警告消息Python 2.6文件存在错误号17,,python,python-2.7,exception,error-handling,path,Python,Python 2.7,Exception,Error Handling,Path,如果文件已经存在,我如何消除错误17并发出警告消息 import os, sys # Path to be created path = "/tmp/home/monthly/daily" try: os.makedirs(path) except OSError as e: if e.errno == 17: //do something os.makedirs( path, 0755 ); print "Path is created" 但是,它仍然显示ERRN
import os, sys
# Path to be created
path = "/tmp/home/monthly/daily"
try:
os.makedirs(path)
except OSError as e:
if e.errno == 17:
//do something
os.makedirs( path, 0755 );
print "Path is created"
但是,它仍然显示ERRNO 17消息。我能做什么?在第一次调用
os.makedirs
之后,将创建目录。(如果目录已经存在,则不进行更改)
第二个调用将始终引发异常
删除对makedirs
的第二个调用:
try:
os.makedirs(path, 0755)
except OSError as e:
if e.errno == 17: # errno.EEXIST
os.chmod(path, 0755)
# os.makedirs( path, 0755 ) <----
试试看:
操作系统makedirs(路径0755)
除O错误为e外:
如果e.errno==17:#errno.EEXIST
os.chmod(路径0755)
#makedirs(path,0755)您可以创建一个变量来查看是否创建了该文件
成功地做到了这一点:
import os, sys
# Path to be created
path = "/tmp/home/monthly/daily"
created = False
is_error_17 = False
try:
os.makedirs(path)
created = True
except OSError as e:
if e.errno == 17:
print 'File has benn created before'
is_error_17 = True
pass
if created == True:
print 'created file successfully'
else:
print 'created file failed.'
if is_error_17 == True:
print 'you got error 17'
在您的代码中,如果第一次尝试捕获错误,则第二个os.makedirs(路径0755);仍将再次引发错误。我想这是您想要的。当发生OSError
错误时,它会检查错误代码,如果它是您感兴趣处理的错误代码,则会打印一条警告消息,否则它只会传播异常。请注意,将可选模式参数用于os.makedirs()
,它将覆盖默认值0777
import errno, os, sys
# Path to be created
path = "/tmp/home/monthly/daily"
try:
os.makedirs(path, 0755)
except OSError as e:
if e.error == errno.EEXIST: # file exists error?
print 'warning: {} exists'.format(path)
else:
raise # re-raise the exception
# make sure its mode is right
os.chmod(path, 0755)
print "Path existed or was created"