使用Python将2个新列写入CSV文件

时间:2016-12-31 14:11:10

标签: python csv

我正在尝试将列添加到“CSV”文件中,我可以从之前的CSV文件中复制但是当我尝试编写接下来的2列时,它只使用最后一行填写其余的speedwind_dirs的行。这两个数字是在for循环中创建的,我应该将它们存储在一个列表中,然后从中写出来吗?任何想法都会很棒。谢谢

with open('latlon.csv', 'r') as csvfile:
    with open('wind2.csv', 'w') as csvoutput:
        towns_csv = csv.reader(csvfile, dialect='excel') # csv reader
        writer = csv.writer(csvoutput, lineterminator='\n') # csv writer
        for rows in towns_csv:
            x = float(rows[2]) #gets x axis
            y = float(rows[1]) # gets y axis
            url = ("http://api.met.no/weatherapi/locationforecast/1.9/?") #start of url string
            lat = "lat="+format(y) #creates the latititue part of the url string
            lon = "lon="+format(x) # creates the longitude part of the url string
            text = url + format(lat) + ";" + format(lon) #combines the strings together to create a new url
            response = requests.get(text) # get the url 
            xml_text=response.text # turns the requested url into a text file
            winds= bs4.BeautifulSoup(xml_text, "xml") #uses BeautifulSoup to make an xml file
            wind_all = winds.find_all("windSpeed") # finds the "windSpeed" element
            speed = wind_all[0].get("mps") # finds the first "mps" attribute
            wind_dir = winds.find_all("windDirection")# finds the "windDirection" element
            wind_dirs = wind_dir[0].get("deg") #finds the "deg" attribute
            new = []
            row = next(towns_csv)
            row.append(speed)
            row.append(wind_dirs)
            new.append(row)
            for item in towns_csv:
                item.append(speed)
                item.append(wind_dirs)
                new.append(item)
                writer.writerow(item)

1 个答案:

答案 0 :(得分:0)

考虑以下调整,包括对字符串格式的稍作修改以及最后一行代码的修改。不需要列表以及最后一个for循环。只需将API数据附加到,这些行是latlong.csv文件的行,并将其写入新文件wind2.csv

import csv
import requests
import bs4

with open('latlon.csv', 'r') as csvfile, open('wind2.csv', 'w') as csvoutput:
    towns_csv = csv.reader(csvfile, dialect='excel')    # csv reader
    writer = csv.writer(csvoutput, lineterminator='\n') # csv writer
    for rows in towns_csv:
        x = float(rows[2])                              # gets x axis
        y = float(rows[1])                              # gets y axis
        url = "http://api.met.no/weatherapi/locationforecast/1.9/?{0};{1}" # start of url string
        lat = "lat={}".format(y)                        # creates the latititue part of the url string
        lon = "lon={}".format(x)                        # creates the longitude part of the url string
        text = url.format(lat, lon)                     # combines the strings together to create a new url
        response = requests.get(text).text              # get the url into text format                           
        winds= bs4.BeautifulSoup(response, "xml")       # uses BeautifulSoup to make an xml file
        wind_all = winds.find_all("windSpeed")          # finds the "windSpeed" element
        speed = wind_all[0].get("mps")                  # finds the first "mps" attribute
        wind_dir = winds.find_all("windDirection")      # finds the "windDirection" element
        wind_dirs = wind_dir[0].get("deg")              # finds the "deg" attribute

        rows.append(speed)                              # append speed value
        rows.append(wind_dirs)                          # append wind value
        writer.writerow(rows)                           # write new row

输入 (latlon.csv)

1   54  -122
2   53  -112
3   52  -102

输出 (wind2.csv)

1   54  -122    1.3    16.2
2   53  -112      4   330.7
3   52  -102    4.9   314.1