将字节字符串写入文件

时间:2014-02-17 16:22:14

标签: lxml

我有以下代码

from lxml import etree
xmlns = "http://www.fpml.org/FpML-5/confirmation"
xsi  = "http://www.w3.org/2001/XMLSchema-instance"
fpmlVersion="http://www.fpml.org/FpML-5/confirmation ../../fpml-main-5-6.xsd http://www.w3.org/2000/09/xmldsig# ../../xmldsig-core-schema.xsd"
page = etree.Element("{"+xmlns+"}dataDocument",nsmap={None:xmlns,'xsi':xsi })
doc = etree.ElementTree(page)
page.set("fpmlVersion", fpmlVersion)
trade = etree.SubElement(page,'trade')
party = etree.SubElement(page,'party',id='party1')
partyID = etree.SubElement(party,'partyID')
partyID.text = 'PARTYAUS33'
partyName = etree.SubElement(party,'partyName')
partyName.text = 'Party A'
party = etree.SubElement(page,'party',id='party2')
partyID = etree.SubElement(party,'partyID')
partyID.text = 'BARCGB2L'
partyName = etree.SubElement(party,'partyName')
partyName.text = 'Party B'
s = etree.tostring(doc, xml_declaration=True,encoding="UTF-8",pretty_print=True)
print (s)

如何将S的内容保存到文件

1 个答案:

答案 0 :(得分:0)

您必须open()二进制模式下的新文件,然后使用文件句柄write()功能,所以添加:

import sys
fd = open(sys.argv[1], 'wb')

一开始。

fd.write(s)

最后。

因此,您现在必须向脚本传递一个额外的参数,这将是要写入的输出文件。另请注意,我在w函数中使用open()标志,该标志将在当前目录中销毁(重新创建)具有该名称的任何文件。

像以下一样运行:

python3 script.py outfile

产量:

<?xml version='1.0' encoding='UTF-8'?>
<dataDocument xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.fpml.org/FpML-5/confirmation" fpmlVersion="http://www.fpml.org/FpML-5/confirmation ../../fpml-main-5-6.xsd http://www.w3.org/2000/09/xmldsig# ../../xmldsig-core-schema.xsd">
  <trade/>
  <party id="party1">
    <partyID>PARTYAUS33</partyID>
    <partyName>Party A</partyName>
  </party>
  <party id="party2">
    <partyID>BARCGB2L</partyID>
    <partyName>Party B</partyName>
  </party>
</dataDocument>