How to add data in xlm file ?
Karim
kliateni at gmail.com
Sat Aug 13 14:49:17 EDT 2016
On 13/08/2016 11:05, Asad ur Rehman wrote:
> def Test(request):
>
> save_path = '/usr/share/newfies/'
>
> name_of_file = ("Avatar")
>
> completeName = os.path.join(save_path, name_of_file+".xlm")
>
> file1 = open(completeName, "w")
>
> toFile = raw_input("Write what you want into the field")
>
> file1.write(toFile)
>
> file1.close()
>
> This is code for save file in specific directory.Output of this file is empty i want to get data from database i write database query in it but it did't work.Example\
>
> def Test(request):
>
> save_path = '/usr/share/newfies/'
>
> name_of_file = ("Avatar")
>
> completeName = os.path.join(save_path, name_of_file+".xlm")
>
> file1 = open(completeName, "w")
>
> toFile = Subscriber.objects.all().count()
>
> file1.write(toFile)
>
> file1.close()
>
>
> Subscriber is table name in my database.
>
> How can i get data ?
> Thanks in advance !
Hello,
Use the standard module (I use python2.7), code not tested If my memory
is good this is the general way to do it:
from xml.dom import minidom
from xml.etree import ElementTree as et
from xml.etree.ElementTree import ElementTree, Element
fname = "my_input_file"
xml_data = et.parse(fname)
root_element = xml_data.getroot()
new_element = et.Element("new_tag")
root_element.append(new_element)
new_element.set('new_attribute', 'attribute value')
fout = "my_ouput_file"
fout.write(prettify(root_element))
Where prettify() is defined by:
def prettify(element):
"""
Pretty print to an indented XML output.
@param element a Element object.
@return a pretty-printed XML string for the element.
"""
# The idea is to print your Element in a string, parse it using
# minidom and convert it again in XML using toprettyxml function.
raw_string = et.tostring(element, encoding='UTF-8', method='xml')
reparsed = minidom.parseString(raw_string)
return reparsed.toprettyxml(indent='\t', encoding='UTF-8')
Cheers
Karim
More information about the Python-list
mailing list