I have a python script which compare IP list with IP Database and gives output of matching criteria. (I got the script from this forum).


    import socket,struct
    for l in open("database.txt"):

    for l in open("iplist.txt"):
        for e in db:
            if e[0]<=ip<=e[1]:
                print l.strip(),e[2],e[3]

The output is in csv format and I want the output in XML, I'm achieving this using AWK command,

awk -F" " 'BEGIN{print"<markers>"} {printf"<marker information=\"%s\" Longitude=\"%s\" Latitude=\"%s\" />\n",$1,$3,$2} END{print"</markers>"}' mapinfo.csv

I can use the following command to combine both,

./convert.py | awk -F" " 'BEGIN{print"<markers>"} {printf"<marker information=\"%s\" Longitude=\"%s\" Latitude=\"%s\" />\n",$1,$3,$2} END{print"</markers>"}'

Any help on how can I use the awk within the python script itself or any other way to display in required format?


<marker information="" Longitude="-79.377040" Latitude="43.641233" />
<marker information="" Longitude="28.043630" Latitude="-26.202270" />
<marker information="" Longitude="-83.227531" Latitude="42.461234" />
<marker information="" Longitude="-118.343030" Latitude="34.091104" />
<marker information="" Longitude="-73.587810" Latitude="45.508840" />
<marker information="" Longitude="67.082200" Latitude="24.905600" />

This example assumes, all the csv contents are lying in a file named a.csv...you can change it to use stdout stream instead of file stream

and out of laziness, i put longitude, latitude as sub-elements.. you can put them as attributes as well

 from xml.etree.ElementTree import Element, SubElement, Comment, tostring

top = Element('markers')
f = open('a.csv')
for line in f:
  split_list = line.strip().split(',')
  information_txt = split_list[0]
  longitude_txt = split_list[1]
  latitude_txt = split_list[2]
  marker = SubElement(top, 'marker')
  info = SubElement(marker, 'information')
  info.text = information_txt
  longitude = SubElement(marker, 'longitude')
  longitude.text = longitude_txt
  latitude = SubElement(marker, 'latitude')
  latitude.text = latitude_txt

print tostring(top)
  • corrected an error... – user93868 Jul 2 '15 at 10:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.