《Python编程:从入门到实践》中csv中for循环问题。

这是我在看加入日期那一段时自己写的代码,不如书中提供的代码简洁高效,但觉得理论上来说没有错误,然而调试时候才发现第二个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)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值