使用 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 = ""
DATAFILE = "745090.csv"


def parse_file(datafile):
name = ""
data = []
with open(datafile,'rb') as f:
Full_data = csv.reader(f)
name = Full_data.next()[1]
for line in Full_data:
data.append(line)
data = data[1:]
# Do not change the line below
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()

Excel 至 CSV

查看 csv 模块文档,了解如何针对 csv.writer 使用不同的分隔符。

# -*- coding: utf-8 -*-
'''
Find the time and value of max load for each of the regions
COAST, EAST, FAR_WEST, NORTH, NORTH_C, SOUTHERN, SOUTH_C, WEST
and write the result out in a csv file, using pipe character | as the delimiter.

An example output can be seen in the "example.csv" file.
'''

import xlrd
import os
import csv
from zipfile import ZipFile

datafile = "2013_ERCOT_Hourly_Load_Data.xls"
outfile = "2013_Max_Loads.csv"


def open_zip(datafile):
with ZipFile('{0}.zip'.format(datafile.split(".")[0]), 'r') as myzip:
myzip.extractall()


def parse_file(datafile):
workbook = xlrd.open_workbook(datafile)
sheet = workbook.sheet_by_index(0)
data = []
header_line_list = sheet.row_values(0)[1:-1]
#print header_line_list
#data.append(header_line_list)
for i in range(8):
temp_result_list = []
temp_list = sheet.col_values(i+1)[1:]
temp_result_list.append(sheet.cell_value(0, i+1))
temp_max = max(temp_list)
temp_time = sheet.cell_value(temp_list.index(temp_max) + 1, 0)
temp_time = xlrd.xldate_as_tuple(temp_time, 0)
temp_result_list.extend((list(temp_time))[0:4])
temp_max = round(temp_max,1)
temp_result_list.append(temp_max)
data.append(temp_result_list)



# YOUR CODE HERE
# Remember that you can use xlrd.xldate_as_tuple(sometime, 0) to convert
# Excel date to Python tuple of (year, month, day, hour, minute, second)
return data

def save_file(data, filename):
with open(filename, 'wb') as csv_outfile:
csvwriter = csv.writer(csv_outfile, delimiter = '|')
csvwriter.writerow(['Station','Year','Month','Day','Hour','Max Load'])
for item in data:
csvwriter.writerow(item)
# YOUR CODE HERE


def test():
open_zip(datafile)
data = parse_file(datafile)
save_file(data, outfile)

number_of_rows = 0
stations = []

ans = {'FAR_WEST': {'Max Load': '2281.2722140000024',
'Year': '2013',
'Month': '6',
'Day': '26',
'Hour': '17'}}
correct_stations = ['COAST', 'EAST', 'FAR_WEST', 'NORTH',
'NORTH_C', 'SOUTHERN', 'SOUTH_C', 'WEST']
fields = ['Year', 'Month', 'Day', 'Hour', 'Max Load']

with open(outfile) as of:
csvfile = csv.DictReader(of, delimiter="|")
for line in csvfile:
station = line['Station']
if station == 'FAR_WEST':
for field in fields:
# Check if 'Max Load' is within .1 of answer
if field == 'Max Load':
max_answer = round(float(ans[station][field]), 1)
max_line = round(float(line[field]), 1)
assert max_answer == max_line

# Otherwise check for equality
else:
assert ans[station][field] == line[field]

number_of_rows += 1
stations.append(station)

# Output should be 8 lines not including header
assert number_of_rows == 8

# Check Station Names
assert set(stations) == set(correct_stations)


if __name__ == "__main__":
test()

Contents
  1. 1. 使用 CSV 模块
  2. 2. Excel 至 CSV