0

I am using ElementTree to get the attributes and elements I need from an xml file. The xml file is queried from mySQL I want to write out all the attributes and elements into a new text file using python

    root = tree.getroot()
    name = root.attrib['name']
    country = root.find("country").text

I can see the results when I print them out I want to write to a file the list of all the names and countries in the xml file

afrobeats
  • 9
  • 3

1 Answers1

0

So if you generate an array with all your XML name's, you can use this few line of code to create/write a .txt file and write all names on a new line.

list_names = ["OLIVIA", "RUBY", "EMILY", "GRACE", "JESSICA"]

with open('listName.txt', 'w') as filehandle:
    # filehandle.writelines("%s\n" % name for name in list_names)
    filehandle.writelines("".join("{0}\n".format(name) for name in list_names))

As @Parfait suggested, here is a solution without % to concatenate string.

Source : https://stackabuse.com/reading-and-writing-lists-to-a-file-in-python/

Zenocode
  • 656
  • 7
  • 19
  • [The new `.format()` method is meant to replace the old `%` formatting syntax. The latter has been de-emphasised, (but not officially deprecated yet).](https://stackoverflow.com/a/13452357/1422451) – Parfait Jul 25 '19 at 14:19