2011-09-24 78 views
0

我有一個下面的python 3腳本,應該下載一個xml文件並將其分成只有500個項目的較小文件。我有兩個問題:XML中的最後一個元素沒有被拾起

  1. 原始的XML最後一個項目是不存在拆分文件
  2. 如果原始的XML爲1000個條目它會創建一個空的3 xml文件。

任何人都可以告訴我在我的代碼中可能會出現這樣的錯誤,導致這些症狀?

import urllib.request as urllib2 
from lxml import etree 

def _yield_str_from_net(url, car_tag): 

    xml_file = urllib2.urlopen(url) 
    for _, element in etree.iterparse(xml_file, tag=car_tag): 
     yield etree.tostring(element, pretty_print=True).decode('utf-8') 
     element.clear() 

def split_xml(url, car_tag, save_as): 

    output_file_num = 1 
    net_file_iter = _yield_str_from_net(url, car_tag) 
    while True: 
     file_name = "%s%s.xml" % (save_as, output_file_num) 
     print("Making %s" % file_name) 
     with open(file_name, mode='w', encoding='utf-8') as the_file: 
      for elem_count in range(500): # want only 500 items 
       try: 
        elem = next(net_file_iter) 
       except StopIteration: 
        return 
       the_file.write(elem) 
       print("processing element #%s" % elem_count) 
     output_file_num += 1 

if __name__ == '__main__': 
    split_xml("http://www.my_xml_url.com/", 
       'my_tag', 
       'my_file') 

回答

1

第二個是沒有錯誤,但通過設計。在讀取1000個元素之後,迭代器還不知道沒有其他項目,因此繼續循環while True

如果迭代器會有hasNext,那麼你可以用while hasNext來替代它以解決這個問題。不幸的是python中沒有這樣的東西。

對於第一個問題:目前我看不到任何代碼解釋此問題。

+0

非常感謝您的幫助 – Milo