您可以将文件对象传递给iterparse
,然后调用f.tell()
. 这将为您提供文件中元素的大致位置。
import lxml.etree as ET
import os
filename = 'data.xml'
total_size = os.path.getsize(filename)
with open(filename, 'r') as f:
context = ET.iterparse(f, events=('end', ), tag='Record')
for event, elem in context:
print(event, elem, float(f.tell())/total_size)
会产生类似的东西
(u'end', <Element Record at 0xb743e2d4>, 0.09652665470688218)
(u'end', <Element Record at 0xb743e2fc>, 0.09652665470688218)
(u'end', <Element Record at 0xb743e324>, 0.09652665470688218)
...
(u'end', <Element Record at 0xb744739c>, 1.0)
(u'end', <Element Record at 0xb74473c4>, 1.0)
(u'end', <Element Record at 0xb74473ec>, 1.0)