《Python编程从入门到实践》记录之Python处理CSV文件数据

目录

1、分析CSV文件(reader()函数、next()函数)

2、打印文件头及其位置

3、提取并读取、显示数据

4、在图表中添加日期(datetime模块)


csv模块包含在Python标准库中,可用于分析CSV文件中的数据行。

1、分析CSV文件(reader()函数、next()函数)

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import csv  # 导入CSV模块
from datetime import datetime

from matplotlib import pyplot as plt

# Get dates, high, and low temperatures from file.
filename = 'sitka_weather_07-2014.csv'
with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader)
    print(header_row)

代码解析:

  • csv.reader()函数,创建一个与该文件关联的阅读器对象。
  • CSV模块包含函数next(),返回文件中的下一行,上述代码只调用了一次next(),得到文件的第一行。
  • 将reader返回的数据存储在header_row中,得到与天气相关的文件头,指出每行包括哪些数据

运行结果:

['AKDT', 'Max TemperatureF', 'Mean TemperatureF', 'Min TemperatureF', 'Max Dew PointF', 
'MeanDew PointF', 'Min DewpointF', 'Max Humidity', ' Mean Humidity', ' Min Humidity', 
' Max Sea Level PressureIn', ' Mean Sea Level PressureIn', ' Min Sea Level PressureIn', 
' Max VisibilityMiles', ' Mean VisibilityMiles', ' Min VisibilityMiles', ' Max Wind SpeedMPH', 
' Mean Wind SpeedMPH', ' Max Gust SpeedMPH', 'PrecipitationIn', ' CloudCover', ' Events', ' WindDirDegrees']

2、打印文件头及其位置

为了让文件头数据更容易理解,将列表中的每个头文件及其位置打印出来:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import csv
from datetime import datetime

from matplotlib import pyplot as plt

# Get dates, high, and low temperatures from file.
filename = 'sitka_weather_07-2014.csv'
with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader)

    for index, colum_header in enumerate(header_row):
        print(index, colum_header)

代码解析:

对列表header_row调用了enumerate来获取每个元素的索引及其值

运行结果:

0 AKDT
1 Max TemperatureF
2 Mean TemperatureF
3 Min TemperatureF
4 Max Dew PointF
5 MeanDew PointF
6 Min Dewpoint
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值