write in xml file in python

To write to an XML file in Python, you will need to use the built-in xml module.

Here is an example of how to create a new XML file and write some basic data into it:

main.py
import xml.etree.ElementTree as ET

# Create a new XML file
root = ET.Element("sample")

# Create child elements
child1 = ET.SubElement(root, "child1")
child1.text = "This is the first child."

child2 = ET.SubElement(root, "child2")
child2.text = "This is the second child."

# Create and save file
tree = ET.ElementTree(root)
tree.write("sample.xml")
352 chars
16 lines

In this example, we first import the xml.etree.ElementTree module. Then, we create a new Element object called root with the tag name "sample". We then create two child elements, child1 and child2, and give them some text content.

Finally, we create an ElementTree object based on root, and use the write method to save the data to a new file called "sample.xml".

related categories

gistlibby LogSnag