如何在Python中获取错误?

时间:2018-01-29 06:36:28

标签: python-3.x error-handling exception-handling

以下代码用于将Excel文档复制到新目录,但我收到一些不同的错误,导致脚本无法完成。

import os
from shutil import copy
for root, dirs, files in os.walk("T:/DIR"):
    for file in files:
        if file.endswith(".xls") or file.endswith('xlsx'):
            copy(os.path.join(root, file),"C:/DIR")

错误的范围从权限错误到文件未找到错误。我需要让脚本通过这些并继续。有关于异常处理的教程,但我不知道如何在我的代码中实际使用它们。例如,this link表示要使用:

except:
    pass

但是我应该把它放在代码中呢?

1 个答案:

答案 0 :(得分:1)

import os
from shutil import copy
for root, dirs, files in os.walk("T:/DIR"):
    for file in files:
        if file.endswith(".xls") or file.endswith('xlsx'):
            try:
                # attempt condition that may cause error
                copy(os.path.join(root, file),"C:/DIR")
            except:
                # handle exception here.
                pass

通常最好处理每种异常的类型 使用except:。您还可以在except:部分记录错误。

阅读Errors and Exceptions上的Python教程,以便更好地理解。

相关问题