How to save multiple xml files in python

Question

I'm attempting to get a series of weather reports from a website, I have the below code which creates the needed URLs for the XMLs I want, what would be the best way to save the returned XMLs with different names?

with open('file.csv') as csvfile:
    towns_csv = csv.reader(csvfile, dialect='excel')
    for rows in towns_csv:
        x = float(rows[2])
        y = float(rows[1])
        url = ("http://api.met.no/weatherapi/locationforecast/1.9/?")
        lat = "lat="+format(y) 
        lon = "lon="+format(x)
        text = url + format(lat) + ";" + format(lon)

I have been saving single XMls with this code;

response = requests.get(text)
xml_text=response.text
winds= bs4.BeautifulSoup(xml_text, "xml") 
f = open('test.xml', "w")
f.write(winds.prettify())
f.close()

The first column of the CSV file has city names on it, I would ideally like to use those names to save each XML file as it is created. I'm sure another for loop would do, I'm just not sure how to create it. Any help would be great, thanks again stack.


Show source
| python   | xml   | save   2016-12-30 11:12 1 Answers

Answers to How to save multiple xml files in python ( 1 )

  1. 2016-12-30 11:12

    You have done most of the work already. Just use rows[0] as your filename. Assuming rows[0] is 'mumbai', then rows[0]+'.xml' will give you 'mumbai.xml' as the filename. You might want to check if city names have spaces which need to be removed, etc.

    with open('file.csv') as csvfile:
        towns_csv = csv.reader(csvfile, dialect='excel')
        for rows in towns_csv:
            x = float(rows[2])
            y = float(rows[1])
            url = ("http://api.met.no/weatherapi/locationforecast/1.9/?")
            lat = "lat="+format(y) 
            lon = "lon="+format(x)
            text = url + format(lat) + ";" + format(lon)
            response = requests.get(text)
            xml_text=response.text
            winds= bs4.BeautifulSoup(xml_text, "xml") 
            f = open(rows[0]+'.xml', "w")
            f.write(winds.prettify())
            f.close()
    

Leave a reply to - How to save multiple xml files in python

◀ Go back