如何解决OS Walk 异常处理
我在异常处理方面不是很有经验。我知道我的代码在到达文件路径中包含“存档”的目录并查看某些文件时会出现一种类型的错误。在文件搜索中,有一些文件被保存为二进制文件,当它通过解析它时,它会给出“ParseError:格式不正确(无效标记):第 1 行,第 0 列”。这是什么类型的异常,我该如何进行定义?我也不知道在哪里查看 python 文档的正确位置。 https://docs.python.org/3/library/exceptions.html#exception-hierarchy
import os
import xml.etree.ElementTree as ET
current_dur = r'Defined Contributions'
for root,dirs,files in os.walk(current_dur):
for file in files:
if file.endswith('.ldm') or file.endswith('.cdm') or file.endswith('.pdm'):
full_file_name = os.path.join(root,file)
print(os.path.join(root,file))
#for i in file_results:
#WE are parseing it.
tree = ET.parse(full_file_name)
#We then get the root.
#Maybe
gotten_root = tree.getroot()
for elm in gotten_root.findall('.//{object}IntraModelReport'):
print(elm.text)
for Model in gotten_root.findall('.//{object}IntraModelReport'):
rootId = elm.attrib
file_Name = Model.find("{attribute}Code").text
unique_ID = Model.find("{attribute}ObjectID").text
employee_badge = Model.find("{attribute}Creator").text
print( file_Name,unique_ID,employee_badge)
解决方法
只需捕获异常并继续。
见https://docs.python.org/3/library/xml.etree.elementtree.html#exceptions
try:
tree = ET.parse(full_file_name)
except xml.etree.ElementTree.ParseError:
print(f'Invalid xml: {full_file_name}')
continue
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。