[英]Recursively parse all xml files and exclude folder
我試圖解析給定文件夾/子文件夾中的所有XML文件,然后搜索並替換該XML中的文本。 全部不包括子文件夾“ Archive”。 我收到錯誤消息“ AttributeError:'NoneType'對象沒有屬性'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
我猜並不是所有的XML標簽都有文本。 所以你應該使用
if elem.text is not None :
try:
print (elem.text)
elem.text = elem.text.replace('_THUMBNAIL.jpg', '.mxd.jpg')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.