2014年6月28日土曜日

開発環境

Head First Python (Paul Barry(著)、 O'Reilly Media )のChapter 8(Mobile app Development: Small devices)、SHARPEN YOUR PENCIL(p.269)を解いてみる。

SHARPEN YOUR PENCIL(p.269)

コード(BBEdit)

athletemodel.py

#!/usr/bin/env python3
#-*- coding: utf-8 -*-

import pickle
import athletelist

def get_coach_data(filename):
    try:
        with open(filename) as f:
            data = f.readline()
        temp = data.strip().split(',')
        return athletelist.AthleteList(temp.pop(0), temp.pop(0), temp)
    except IOError as ioerr:
        print('File error (get_coach_data): {0}'.format(ioerr))
        return None

def put_to_store(files_list):
    athletes = {}
    for file in files_list:
        athlete = get_coach_data(file)
        athletes[athlete.name] = athlete
    try:
        with open('athletes.pickle', 'wb') as f:
            pickle.dump(athletes, f)
    except IOError as ioerr:
        print('File error (put_and_store): {0}'.format(ioerr))
    return athletes

def get_from_store():
    athletes = {}
    try:
        with open('athletes.pickle', 'rb') as f:
            athletes = pickle.load(f)
    except IOError as ioerr:
        print('File error (get_from_store): ' + str(ioerr))
    return athletes

def get_names_from_store():
    athletes = get_from_store()
    return [athlete for athlete in athletes]

if __name__ == '__main__':
    print(get_names_from_store())

入出力結果(Terminal)

$ ./athletemodel.py 
['James Lee', 'Sarah Sweeney', 'Mikey McManus', 'Julie Jones']
$

0 コメント:

コメントを投稿