Python (and coding newbie) here. I'm attempting to generate an XML file based a list of files in a directory. The first two letters of the filenames correspond to a new letter country code and I'm trying to extract this as well.
My intended format is as follows:
<ROOT>
<BASIC/>
<FULL>
<INFO>
<server>filname</server>
<country>country</country>
<region/>
</INFO>
</FULL>
</ROOT>
I seem to be able to generate the XML file but I'm unable to convert the two digit country code to the country using pycountry. Could someone please suggest a possible solution? Any comments on the rest of the code would be helpful as well.
# -*- coding: utf-8 -*-
import lxml.etree as xml
import pycountry
import glob
import gettext
gettext.bindtextdomain('iso3166', pycountry.LOCALES_DIR)
_c = lambda t: gettext.dgettext('iso3166', t)
def createXML(outfile):
root = xml.Element("ROOT")
basic = xml.Element("BASIC")
full = xml.Element("FULL")
root.append(basic)
root.append(full)
# add file information
for filename in glob.glob("*.*"):
info = xml.Element("INFO")
server = xml.SubElement(info, "server")
server.text = filename
short = filename[:2]
country = xml.SubElement(info, "country")
def get_country(code):
return _c(pycountry.countries.get(alpha2=code).name)
country.text = get_country(short)
region = xml.SubElement(info, "region")
full.append(info)
print xml.tostring(root, pretty_print=True)
#save new XML
# tree = xml.ElementTree(root)
# with open(filename, "w") as fh:
# tree.write(fh)
#--------------------------------------------------------
if __name__ == "__main__":
createXML("info.xml")
Thanks to gbe for the help! It's not pretty but here is the code that worked.
# -*- coding: utf-8 -*-
import lxml.etree as xml
import pycountry
import glob
import gettext
gettext.bindtextdomain('iso3166', pycountry.LOCALES_DIR)
_c = lambda t: gettext.dgettext('iso3166', t)
def createXML(outfile):
root = xml.Element("ROOT")
basic = xml.Element("BASIC")
full = xml.Element("FULL")
root.append(basic)
root.append(full)
# add file information
for filename in glob.glob("*.*"):
info = xml.Element("INFO")
server = xml.SubElement(info, "server")
server.text = filename
short = filename[:2].upper()
country = xml.SubElement(info, "country")
country.text = pycountry.countries.get(alpha2=short).name
region = xml.SubElement(info, "region")
full.append(info)
print xml.tostring(root, pretty_print=True)
#save new XML
# tree = xml.ElementTree(root)
# with open(filename, "w") as fh:
# tree.write(fh)
#--------------------------------------------------------
if __name__ == "__main__":
createXML("info.xml")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.