gpt4 book ai didi

python-3.x - 如何获取过去的Python错误?

转载 作者:行者123 更新时间:2023-12-03 08:23:58 25 4
gpt4 key购买 nike

以下代码用于将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教程以获得更好的理解。

关于python-3.x - 如何获取过去的Python错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48495629/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com