构造模块
模块athletelist并安装。模块athletelist 内容如下:
class AthleteList(list):
def __init__(self,a_name,a_dob=None,a_times=[]):
list.__init__([])
self.name=a_name
self.dob=a_dob
self.extend(a_times)
def tops3(self):
return(sorted(set([sanitize(t)for t in self]))[0:3])
def sanitize(time_string):
if '-' in time_string:
splitter='-'
elif ':' in time_string:
splitter=':'
else:
return(time_string)
(mins,secs)=time_string.split(splitter)
return(mins + '.' + secs)
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: ' + str(ioerr))
return (None)数据的存储和取出import pickle
from athletelist import AthleteList
import os
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: ' + str(ioerr))
return (None)
def put_to_store(files_list):
all_athletes={}
for each_file in files_list:
ath=get_coach_data(each_file)
all_athletes[ath.name]=ath
try:
with open('athletes.pickle','wb') as athf:
pickle.dump(all_athletes,athf)
except IOError as ioerr:
print('File Error: ' + str(ioerr))
return (all_athletes)
def get_from_store():
all_athletes={}
try:
with open('athletes.pickle','rb') as athf:
all_athletes=pickle.load(athf)
except IOError as ioerr:
print('File Error:(get_from_store): ' + str(ioerr))
return(all_athletes)
os.chdir('D:/HeadFirstPython/webapp/data')
os.getcwd()
the_files=['sarah.txt','julie.txt','james.txt','mikey.txt']
data=put_to_store(the_files)
print(data)
data_copy=get_from_store()
for each_athlete in data_copy:
print(data_copy[each_athlete].name + ' '+data_copy[each_athlete].dob)
查看输出:
RESTART: C:/Users/ThinkPad/AppData/Local/Programs/Python/Python36-32/chapter7/c7-223.py
{'Sarah Sweeney': ['2:58', '2.58', '2:39', '2-25', '2-55', '2:54', '2.18', '2:55', '2:55', '2:22', '2-21', '2.22'], 'Julie Jones': ['2.59', '2.11', '2:11', '2:23', '3-10', '2-23', '3:10', '3.21', '3-21', '3.01', '3.02', '2:59'], 'James Lee': ['2-34', '3:21', '2.34', '2.45', '3.01', '2:01', '2:01', '3:10', '2-22', '2-01', '2.01', '2:16'], 'Mikey McManus': ['2:22', '3.01', '3:01', '3.02', '3:02', '3.02', '3:22', '2.49', '2:38', '2:40', '2.22', '2-31']}
Sarah Sweeney 2002-6-17
Julie Jones 2002-8-17
James Lee 2002-3-14
Mikey McManus 2002-2-24
>>> dir()
['AthleteList', '__annotations__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'data', 'each_athlete', 'get_coach_data', 'get_from_store', 'os', 'pickle', 'put_to_store', 'the_files']
本文介绍了一个用于管理运动员成绩数据的Python模块AthleteList。该模块能够读取文件中的运动员信息,并提供存储和检索功能。通过使用pickle模块进行序列化,可以将数据持久化存储到磁盘上,便于后续的数据管理和分析。
1225

被折叠的 条评论
为什么被折叠?



