2012-03-14 160 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