head first python菜鸟学习笔记(第七章) ——web应用之为数据建模

问题1.

#意思是从athletelist.py中导入AthleteList
from athletelist import AthleteList

源程序代码

import pickle
from athletelist import AthleteList

报错:

原因:

#意思是从athletelist.py中导入AthleteList
from athletelist import AthleteList

而我的程序里,包含类AthleteList的py文件名为Athlete。

更改后则成功:

import pickle
from Athlete import AthleteList

数据建模的完整代码:

import pickle
from Athlete import AthleteList

def get_coach_data(filename):
        try:
                with open(filename) as f:
                        data=f.readline()
                templ=data.strip().split(',')
                return(AthleteList(templ.pop(0),templ.pop(0),templ))
        except IOError as ioerr:
                print('File error(get_coach_data):'+str(ioerr))

def put_to_store(file_list):
        '''
       需要在这里编写代码,用文件中的数据填充字典
       不要忘记把这个字典保存到一个pickle中,还应检查文件I/O错误
       返回一个AthleteList字典
        '''
        all_athletes={}
        for each_file in file_list:
                
                '''将各个文件转化为一个AthleteList对象实例,并把选手的数据增加到字典'''
                ath=get_coach_data(each_file)
                all_athletes[ath.name]=ath
                '''每个选手的名字作为键,值是AthleteList对象实例'''
        try:
                with open('athlete.pickle','wb')as athf:
                        pickle.dump(all_athletes,athf)
                        '''
                        output = open('data.pkl', 'wb')
                        pickle.dump(data1, output)
                        以二进制写入的方式打开文件athlete.pickle,并把all_athletes写入到该文件中
                        '''
        except IOError as ioerr:
                print('File error(put_and_store):'+str(ioerr))
        return(all_athletes)
                
def get_from_store():
        '''
        从文件得到字典,从而返回给调用者
        '''
        all_athletes={}
        try:
                with open('athlete.pickle','rb') as athf:
                        all_athletes=pickle.load(athf)
        except IOError as ioerr:
                print('File error(get_from_data):'+str(ioerr))
        return(all_athletes)




    
        

 

转载于:https://www.cnblogs.com/hebulingding/p/7598525.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值