save input from list in xml text in python

Here's an example of how to save input from a list to an XML file in Python:

main.py
import xml.etree.ElementTree as ET

# define your list
my_list = ['apple', 'banana', 'cherry', 'date']

# create the root element
root = ET.Element("fruits")

# loop through the list and add each item as a child element of the root element
for item in my_list:
    fruit = ET.SubElement(root, "fruit")
    fruit.text = item

# create the XML document
tree = ET.ElementTree(root)

# write the XML document to a file on disk
tree.write("fruits.xml")
448 chars
19 lines

In this example, we first import the xml.etree.ElementTree module. Then we define our list my_list and create a new root element fruits.

Next, we loop through the list and create a new child element fruit for each item in the list. We set the text of each child element to the corresponding item in the list.

After we have created the entire XML document, we create an ElementTree object from the root element and write the XML document to a file called fruits.xml.

You can modify this example to work with your specific list and file output format.

related categories

gistlibby LogSnag