繁体   English   中英

python解析/处理文件夹中的所有xml文件

[英]python parse/process all xml files in folder

我试图在文件夹中的所有 xml 文件上运行我的代码我在运行代码时遇到一些错误并且它生成了一些文件但不是全部

这是我的代码:

import xml.etree.ElementTree as ET
import os
import glob
path = 'C:/xml/'

for infile in glob.glob( os.path.join(path, '*.xml') ):
        tree = ET.parse(infile)
        root = tree.getroot()
        with open(infile+'new.csv','w') as outfile:
            for elem in root.findall('.//event[@type="MEDIA"]'):
                    mediaidelem = elem.find('./mediaid')
                    if mediaidelem is not None:
                            outfile.write("{}\n".format(mediaidelem.text))

这是所有的错误日志

Traceback (most recent call last):
  File "C:\xml\2.py", line 8, in <module>
    tree = ET.parse(infile)
  File "C:\Python34\lib\xml\etree\ElementTree.py", line 1187, in parse
    tree.parse(source, parser)
  File "C:\Python34\lib\xml\etree\ElementTree.py", line 598, in parse
    self._root = parser._parse_whole(source)
  File "<string>", line None
xml.etree.ElementTree.ParseError: no element found: line 1, column 0

考虑到错误消息,您可能有一些空(或格式错误)的文件。

我会在此处添加错误处理以警告用户此类错误,然后跳过该文件。 就像是:

for infile in glob.glob( os.path.join(path, '*.xml') ):
    try:
        tree = ET.parse(infile)
    except xml.etree.ElementTree.ParseError as e:
        print infile, str(e)
        continue
    ...

我没有试图在这里重现它,这只是一个猜测。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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