使用python读取csv文件格式

时间:2017-07-08 21:49:48

标签: python csv

我正在尝试从csv格式的文件中读取天气数据。我打印了文件的索引和标题,我看到日期的索引为零。我尝试在python中使用datetime模块来访问日期,它告诉我有一个索引错误。这是我收到的错误消息:

Traceback (most recent call last):
  File "accra_weather.py", line 15, in <module>
    current_date = datetime.strptime(row[0], "%Y-%m-%d")
IndexError: list index out of range

这是完整的代码:

import csv
from datetime import datetime

filename = "accra_month.csv"
with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader)

    dates, highs = [], []
    for row in reader:
        try:
           current_date = datetime.strptime(row[0], "%Y-%m-%d")
           high = int(row[1])
        except ValueError:
            print(date, "Missing data")
        else:
            highs.append(high)
            dates.append(current_date)

这也是我试图检查的天气数据:

GMT,Max TemperatureC,Mean TemperatureC,Min TemperatureC,Dew PointC,MeanDew PointC,Min DewpointC,Max Humidity, Mean Humidity, Min Humidity, Max Sea Level PressurehPa, Mean Sea Level PressurehPa, Min Sea Level PressurehPa, Max VisibilityKm, Mean VisibilityKm, Min VisibilitykM, Max Wind SpeedKm/h, Mean Wind SpeedKm/h, Max Gust SpeedKm/h,Precipitationmm, CloudCover, Events,WindDirDegrees
2017-6-1,33,29,26,26,24,23,94,78,56,1016,1014,1012,18,11,6,27,11,,0.00,2,,234
2017-6-2,32,29,26,26,26,25,94,83,62,1016,1014,1012,18,11,8,26,14,,0.00,3,,217
2017-6-3,31,28,26,26,26,22,94,86,61,1015,1012,1011,18,10,8,37,18,,0.76,5,Thunderstorm,214

0 个答案:

没有答案