【发布时间】:2017-02-13 20:02:08
【问题描述】:
我正在尝试解析给定文件夹/子文件夹中的所有 XML 文件,并搜索和替换该 XML 中的文本。同时排除子文件夹“存档”。我收到错误“AttributeError: 'NoneType' object has no attribute 'replace'”不确定我缺少什么,但是一旦到达 ElementTree 打开并解析 XML,我的循环似乎就死了。
for roots, dirs, files in os.walk("C:\test", topdown=True):
if 'Archive' in dirs:
dirs.remove('Archive')
#dirs[:] = [d for d in dirs if 'Archive' not in d]
for f in files:
if f.endswith('.xml'):
try:
with open(os.path.join(roots, f), 'r') as xml:
tree = ET.parse(xml)
root = tree.getroot()
for elem in root.getiterator():
try:
print (elem.text)
elem.text = elem.text.replace('_THUMBNAIL.jpg', '.mxd.jpg')
except ET.ParseError:
pass
tree.write(xml, encoding='utf-8')
except FileNotFoundError:
pass
【问题讨论】:
标签: python xml lxml elementtree