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

时间:2012-03-14 16:38:56

标签: 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)

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

1 个答案:

答案 0 :(得分:3)

  

如果遇到异常,我怎么能这样做呢?它会移动文件并跳转到下一个文件?

只需使用continue

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