处理提供的文件,并使用 csv 模块从中提取文件

#!/usr/bin/env python
"""
Your task is to process the supplied file and use the csv module to extract data from it.
The data comes from NREL (National Renewable Energy Laboratory) website. Each file
contains information from one meteorological station, in particular - about amount of
solar and wind energy for each hour of day.

Note that the first line of the datafile is neither data entry, nor header. It is a line
describing the data source. You should extract the name of the station from it.

The data should be returned as a list of lists (not dictionaries).
You can use the csv modules "reader" method to get data in such format.
Another useful method is next() - to get the next line from the iterator.
You should only change the parse_file function.
"""
import csv
import os

DATADIR = "./data/"
DATAFILE = "745090.csv"            


def parse_file(datafile):
    name = None
    header = None
    data = []
    with open(datafile,'rb') as f:
        r = csv.reader(f)       数据应该返回为包含列表的列表(而不是字典)。你可以使用模块“reader”方法获取此类格式的数据

        for line in r:
            # get the name
            if not name:
                name = line[1]
                continue
                
            # get the header
            if not header:
                header = line
                continue
            
            # add the list for the current line to `data`
            data.append(line)
                
    return (name, data)


# from the instructor
def parse_file(datafile):
    with open(datafile,'rb') as f:
        r = csv.reader(f)
        name = r.next()[1]         next(),可以用来获取迭代器中的下一行
        header = r.next()
        data = [row for row in r]
                
    return (name, data)


def test():
    datafile = os.path.join(DATADIR, DATAFILE)
    name, data = parse_file(datafile)

    assert name == "MOUNTAIN VIEW MOFFETT FLD NAS"
    assert data[0][1] == "01:00"
    assert data[2][0] == "01/01/2005"
    assert data[2][5] == "2"


if __name__ == "__main__":
    test()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值