【问题标题】:Write the output of an lxml parse to a new file将 lxml 解析的输出写入新文件
【发布时间】:2013-10-03 11:00:45
【问题描述】:

我一直在这个论坛上获得帮助来解析 xml 文件并提取某些值。我可以使用以下命令成功地将所需的值打印到屏幕上:

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(我在其他地方使用过),但这似乎不是解决方案。我也看了元素树'write'命令,但不明白怎么实现。

有人可以建议如何从 lxml 输出构造字符串并将其写入文件吗?

【问题讨论】:

    标签: xml file lxml


    【解决方案1】:

    使用open 以写入模式(w)打开输出文件,然后使用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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-11
      • 1970-01-01
      • 1970-01-01
      • 2013-04-05
      相关资源
      最近更新 更多