如何获取 Python 中的过去错误?
How to get past errors in Python?
以下代码用于将 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
但是我到底应该把它放在代码的什么地方呢?
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 教程以更好地理解。
以下代码用于将 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
但是我到底应该把它放在代码的什么地方呢?
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 教程以更好地理解。