在python中,如何忽略异常并处理奇数代码?

2024-04-27 04:19:52 发布

您现在位置:Python中文网/ 问答频道 /正文

样品:

with suppress(Exception)
    os.remove('test1.log')
    os.remove('test2.log')

try:
    os.remove('test1.log')
    os.remove('test2.log')
except:
    pass

如果test1.log不存在,test2.log将不会被删除,因为FileNotFoundError。那么,如何在异常发生后处理奇数代码,或者如何防止抛出异常呢?你知道吗


Tags: logoswithexception样品pass后处理remove
3条回答

提图斯班已经给出了一个有效的解决方案。 您还可以简单地将语句放入for循环,这是一种较短的语法,因为您不必重复try-catch块(在尝试删除两个以上的项时尤其有用)。你知道吗

lst = ["test1.log","test2.log"]
for element in lst:
    try:
        os.remove(element)
    except:
        pass

try-except中,如果触发了异常,它将转到except部分,然后从那里继续。因此,如果要确保同时尝试remove,请执行以下操作:

try:
    os.remove('test1.log')
except:
    pass

try:
    os.remove('test2.log')
except:
    pass

或者,您可以在删除文件之前尝试检查文件是否存在:

if os.path.exists('test1.log'):
   os.remove('test1.log')
if os.path.exists('test2.log'):
   os.remove('test2.log')

正如副本所解释的,您不能仅仅抑制异常。你知道吗

你可能想要这样的东西:

files = ["test1.log", "test2.log"]
for file in files:
    try:
        os.remove(file)
    except:
        pass

相关问题 更多 >