我怎么能是否存在一个目录与Python 2.7使用os / app
删除一个文件?
我试着
os.remove('directory/file.png')
但如果该项目不存在的,我得到了一个错误。
try:
os.remove(path)
except OSError:
pass
刚刚捕获错误并忽略它。 (忽略错误是不是你对所有错误做,但在这里,它就是你想要的。)
if os.path.exists(path):
os.remove(path)
检查是否存在先:
if os.path.exists(path):
os.remove(path)
使用异常:
try:
os.remove("file_name")
except:
return "something went wrong"