在python中将行写入文本文件

时间:2015-11-03 19:01:06

标签: python xml python-3.4

我一直在尝试在python

中写一个XML语句

我需要将以下内容写入XML

  <SimBase.Document Type="Launch" version="1,0">
  <Descr>Launch</Descr>
  <Filename>dll.xml</Filename>
  <Disabled>False</Disabled>
  <Launch.ManualLoad>False</Launch.ManualLoad>
  <Launch.Addon>
    <Name>jb777 Panel Loader</Name>
    <Disabled>False</Disabled>
    <Path>Modules\jb777loader.dll</Path>
  </Launch.Addon>
  <Launch.Addon>
    <Name>jb777 fmc</Name>
    <Disabled>False</Disabled>
    <Path>Modules\jb777_fmc.dll</Path>
    <DllStartName>module_init</DllStartName>
    <DllStopName>module_deinit</DllStopName>
  </Launch.Addon>
</SimBase.Document>

我如何将其写入XML

先谢谢

1 个答案:

答案 0 :(得分:3)

在python中创建数据并将其写入文件就像打开文件一样简单

file_obj = open("xml_file.xml", 'wb')

如果您已有数据,

file_data = """<SimBase.Document Type="Launch" version="1,0">
  <Descr>Launch</Descr>
  <Filename>dll.xml</Filename>
  <Disabled>False</Disabled>
  <Launch.ManualLoad>False</Launch.ManualLoad>
  <Launch.Addon>
    <Name>jb777 Panel Loader</Name>
    <Disabled>False</Disabled>
    <Path>Modules\jb777loader.dll</Path>
  </Launch.Addon>
  <Launch.Addon>
    <Name>jb777 fmc</Name>
    <Disabled>False</Disabled>
    <Path>Modules\jb777_fmc.dll</Path>
    <DllStartName>module_init</DllStartName>
    <DllStopName>module_deinit</DllStopName>
  </Launch.Addon>
</SimBase.Document>"""

file_obj.write(file_data)
file_obj.close()