2013-10-03 39 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))