0

このフォーラムで、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 (他の場所で使用したもの) を試してみましたが、これは解決策ではないようです。要素ツリーの「書き込み」コマンドも見ましたが、実装方法がわかりません。

lxml 出力から文字列を作成してファイルに書き込む方法を教えてもらえますか?

4

1 に答える 1

0

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))
于 2013-10-03T11:04:58.177 に答える