Forum Archive

Pythonista creates empty XML file!

djorge

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>
'''
Phuket2

@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>
'''
cvp

Initial code is ok if you terminate by

f.close()

Because you didn't really write on disk before the close

zrzka

Should be enough without f.close(). Becase with open is a context manager, which closes the file automatically.

Phuket2

@zrzka , @djorge post was not using the context manager. I added that when i was testing

djorge

@Phuket2 adding w+ solved the problem. Thank you very much to all.

djorge

@cvp this solution also solved my problem. Thank you

zrzka

Ahh, I see, I thought that you just replaced w with w+ and the context manager was already there. Sorry.