这是我在看加入日期那一段时自己写的代码,不如书中提供的代码简洁高效,但觉得理论上来说没有错误,然而调试时候才发现第二个for循环根本么有执行,打印出的dates也是个空列表,这是为什么,请教各位大神!
import csv
from datetime import datetime
from matplotlib import pyplot as plt
# 一、分析csv文件头
filename = 'Beijing.csv'
# 若不传递参数encoding='utf-8',
# 则会报错UnicodeDecodeError: 'gbk' codec can't decode byte 0xad in position 887:
# illegal multibyte sequence
# 从文件中获取最高气温
with open(filename, encoding='utf-8') as f:
# 创建与该文件相关联的阅读器对象,存储在reader中
reader = csv.reader(f)
# next返回下一行,因为只调用一次,所以返回的是第一行(列表形式)
header_row = next(reader)
print(header_row)
highs = []
dates = []
# 从第二行开始遍历(row:行)每行的row[1]即为第二列
for row in reader:
# current_date = datetime.strptime(row[0], '%Y-%m-%d')
# dates.append(current_date)
# 将字符串转换为int,才能让matplotlib读取它们
high = int(row[1])
highs.append(high)
for row in reader:
current_date = datetime.strptime(row[0], "%Y-%m-%d")
dates.append(current_date)
print(dates)
print(highs)