2016-12-30 9 views
0

ウェブサイトから一連の天気予報を取得しようとしていますが、私が望むXMLのために必要なURLを作成する以下のコードがあります。返されるXMLは異なる名前で返されますか?複数のxmlファイルをPythonで保存する方法

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) 

私はこのコードで単一のXMlsを保存しています。

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() 

CSVファイルの最初の列は、その上に都市名を持って、私は、理想的には、それが作成される各XMLファイルを保存するために、これらの名前を使用したいと思います。私はループのために別のものがあると確信しています、私はそれを作成する方法がわかりません。 助けて頂ければ幸いです。もう一度スタックしてください。

答えて

0

すでにほとんどの作業を完了しています。ファイル名にはrows[0]を使用してください。 rows[0]が「mumbai」であると仮定すると、rows[0]+'.xml'はファイル名として'mumbai.xml'を与えます。都市名にスペースなどがある場合は、削除する必要があります。

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() 
関連する問題