简体   繁体   中英

Recursively parse all xml files and exclude folder

I am trying to parse all XML files in a given folder/subfolders and search and replace text inside that XML. All while excluding the subfolder "Archive". I am getting the error "AttributeError: 'NoneType' object has no attribute 'replace'" Not sure what I am missing, but my loop seems to die once it reaches the ElementTree to open and parse the 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

I guess that not all XML tags have a text. So you should use

if elem.text is not None :
    try:
        print (elem.text)
        elem.text = elem.text.replace('_THUMBNAIL.jpg', '.mxd.jpg')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM