import os
os.chdir('C:\\Users\\Sonia\\Desktop\\Headfirstpython\\handledata2') #切换文件目录
'''将时间转换为mins.secs的格式'''
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 read(filename,separator = ','):
try:
with open(filename,"r") as file:
data = file.readline()
#return(data.strip().split(separator)
list = data.strip().split(separator)
name = list[0]
birth_day = list[1]
list.pop(0)
list.pop(0)
print('姓名:'+name)
print('出生年月日:'+birth_day)
sort_list = sorted(set(sanitize(each_item) for each_item in list))
print('成绩:'+str(sort_list))
except IOError as err:
print('File Error:' + str(err))
return(None)
#方法②,使用数据字典
def get_coach_data(filename,separator = ','):
try:
with open(filename,"r") as file:
data = file.readline()
temp = data.strip().split(separator)
dict_file={'name':temp.pop(0),'birthday':temp.pop(0),'times':temp}
print('name:'+dict_file['name'])
print('times:'+str(sorted(set([sanitize(t) for t in dict_file['times']]))[0:3]))
except IOError as err:
print('File Error:' + str(err))
return(None)
get_coach_data('james2.txt')
get_coach_data('julie2.txt')
get_coach_data('mikey2.txt')
get_coach_data('sarah2.txt')
运行结果:
name:James Lee
times:['2.01', '2.16', '2.22']
name:Julie Jones
times:['2.11', '2.23', '2.59']
name:Mikey McManus
times:['2.22', '2.31', '2.38']
name:Sarah Sweeney
times:['2.18', '2.21', '2.22']