2013-10-03 41 views
0

我一直在接受本論壇上的幫助來解析xml文件並提取某些值。我可以成功地打印所需的值到屏幕上,使用下面的:將lxml解析的輸出寫入一個新文件

for info in root.xpath('//xmlns:ProgramInformation', namespaces=nsmap): 

    print (info.get('programId')) # retrieve crid 
    print (info.find('.//xmlns:Title', namespaces=nsmap).text) # retrieve title 
    print (info.find('.//xmlns:Genre/xmlns:Name', namespaces=nsmap).text) # retrieve genre 

我現在需要的輸出寫入一個文件(不是XML格式,但在格式ABC | DEF | GHI,每組在一條新的線上)。

我嘗試過使用fo.write(我在別處使用過),但這似乎並不是解決方案。我也看了元素樹'寫'命令,但我不明白如何實現它。

有人可以建議如何從lxml輸出構造字符串並將其寫入文件?

回答

0

用寫入模式(w)使用open打開輸出文件,然後使用file.write寫入文件。

with open('output.txt', 'w') as f: 
    for info in root.xpath('//xmlns:ProgramInformation', namespaces=nsmap): 
     crid = (info.get('programId')) # retrieve crid 
     title = (info.find('.//xmlns:Title', namespaces=nsmap).text) # retrieve title 
     genre = (info.find('.//xmlns:Genre/xmlns:Name', namespaces=nsmap).text) # retrieve genre 
     f.write('{}|{}|{}\n'.format(crid, title, genre))