python - 如果遇到异常则跳过 XML 读取循环的迭代 Python

标签 python mysql xml sorting lxml

我有一个函数可以从 XML 文件中读取某些标签。我试图做到这一点,以便如果标签不存在(标签分配的变量失败),则会调用异常并将文件移动到不同的目录并读入下一个文件。

这是我的功能:

def iterateOverXml():
    localPath = "C:\local"
    remotePath = "C:\outbox"
    errorPath = "C:\Error"
    xmlFiles = glob.glob1(localPath,"*.xml")
    for file in xmlFiles:
        print file
        a = os.path.join(localPath,file)
        element = etree.parse(a)


        try:
            data= element.xpath('//Foobar/Data/node()')
            parsedData = [{field.tag: field.text for field in data} for action in data]
            xmlType = parsedData[0]['FormType']
        except:
            shutil.move(os.path.join(localPath,file),errorPath)


        if xmlType == 'record':
            parseTitle(element)
            parseTracks(element)
            parseArtist(element)
            shutil.move(os.path.join(localPath,file),remotePath)

如果遇到异常,我怎样才能做到既移动文件又停止当前迭代并调用下一个文件?

最佳答案

How can I make it so if the exception is met it both moves the file and skips to the next file?

只需使用继续:

for file in xmlFiles:
    # ...

    try:
        # ....
    except:
        shutil.move(os.path.join(localPath,file),errorPath)
        continue  # <---- Will continue at the top of the for loop
                  #       with the next file in xmlFiles

关于python - 如果遇到异常则跳过 XML 读取循环的迭代 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9706149/

相关文章:

java - 解析生命周期处理指令时出错

java - 将嵌套 XML 文件解析为节点集

xml - 如何使用正则表达式操作来自 SOAP XML 的数据

python - 使用 Plink (PuTTy) 通过 Python 进行 SSH

mysql - 如何根据 WHERE 和 AND 更新 2 个不同的行

python - 适用于Windows初学者的Python IDE/环境

java - 如何将学生添加到学生组

mysql - 连续非空值的计数

python - 优雅处理 "MySQL has gone away"

python - jsonify flask-sqlalchemy flask中的多对一关系