2012-03-14 161 views
0

我有一个从XML文件中读取某些标记的函数。我试图这样做,以便如果标记不存在(标记赋值变量失败),则调用异常并将文件移动到不同的目录并读入下一个文件。如果遇到异常,跳过XML读循环的迭代Python

Here我的功能:

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) 

我怎样才能使它所以如果异常满足它既移动当前迭代停止文件和下一个文件叫什么名字?

+0

你是什么意思 “跳到下一行” 呢? – 2012-03-14 16:41:02

+0

停止当前迭代并读取下一个文件。 – user1130161 2012-03-14 16:41:34

+0

顺便说一句,如果你想把一个字符串'\'放在一个字符串中,你应该把它写成'\\',或者使用'raw strings'('r“C:\ ...”'' \'是转义字符。 – 2012-03-14 16:44:24

回答

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 
+0

因此,这将打破目前的文件迭代,并重新开始? – user1130161 2012-03-14 16:42:48

+0

它不会重新开始,它会跳过当前迭代并继续下一个迭代。 – 2012-03-14 16:46:20