Welcome!
This is the community forum for my apps Pythonista and Editorial.
For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.
Pythonista creates empty XML file!
-
Hi,
I'm struggling with a weird problem with saving xml a file.
I tested this in a pc and the file is created with the xml.In pythonista the file is created but it is empty.
What might be the problem?Here is the simple code:
#coding: utf-8 #!python2 import xml.etree.ElementTree as et substring_xml_file = u"Category_Substring_test.xml" cat = "Compras" descricao_str_r = "Supermercado" root = et.Element("root") a = et.SubElement(root, u"CategoryEntry") a.set(u"Category", cat) a.set(u"Payee", " ") a.set(u"SubString", descricao_str_r) f = open(substring_xml_file, "w") tree = et.ElementTree(root) tree.write(f, encoding=u"UTF-8", xml_declaration=True) #Category_Substring_test.xml content should be: ''' <?xml version='1.0' encoding='UTF-8'?> <root><CategoryEntry Category="Compras" Payee=" " SubString="Supermercado" /></root> '''
-
@djorge , not that i really know why. But the below seems to fix it "w+". I just played around to see if it could get it.
#coding: utf-8 #!python2 import xml.etree.ElementTree as et substring_xml_file = u"Category_Substring_test.xml" cat = "Compras" descricao_str_r = "Supermercado" root = et.Element("root") a = et.SubElement(root, u"CategoryEntry") a.set(u"Category", cat) a.set(u"Payee", " ") a.set(u"SubString", descricao_str_r) with open(substring_xml_file, "w+") as f: tree = et.ElementTree(root) tree.write(f, encoding=u"UTF-8", xml_declaration=True) #Category_Substring_test.xml content should be: ''' <?xml version='1.0' encoding='UTF-8'?> <root><CategoryEntry Category="Compras" Payee=" " SubString="Supermercado" /></root> '''
-
Initial code is ok if you terminate by
f.close()
Because you didn't really write on disk before the close
-
Should be enough without f.close(). Becase with open is a context manager, which closes the file automatically.
-
-
@Phuket2 adding w+ solved the problem. Thank you very much to all.
-
@cvp this solution also solved my problem. Thank you
-
Ahh, I see, I thought that you just replaced w with w+ and the context manager was already there. Sorry.