Use pickle to save, read files
#dump.pyimport pickletry: with open(‘data.pickle‘,‘wb‘) as data: pickle.dump([1,2,‘three‘],data)except IOError as err: print(‘file error:‘ + str(err))except pickle.PickleError as perr: print(‘pickling error:‘ + str(perr))
#load.pyimport pickletry: with open(‘data.pickle‘,‘rb‘) as data: a_list = pickle.load(data) print a_listexcept IOError as err: print(‘file error:‘+str(err))except pickle.PickleError as perr: print(‘pickling error:‘+str(perr))
$ python dump.py $ python load.py [1, 2, ‘three‘]
The fifth chapter deals with data
Read the four score data downloaded from the head first Python website and format the data:
#print_times.pydef print_times(file_name): time_list = [] try: with open(file_name+‘.txt‘) as data: time_list = data.read().replace(‘-‘,‘:‘).replace(‘.‘,‘:‘) time_list = time_list.strip().split(‘,‘) except IOError as err: print(‘file error:‘+str(err)) return time_list
Print test:
- Ctrl+a,ctrl+e shortcut keys available in Mac Terminal Jump to the beginning or end of a line
Derivation list
Convert a list to a different list with some sort of rule
>>>james = print_times.print_times(‘james‘)>>> james[‘2:34‘, ‘3:21‘, ‘2:34‘, ‘2:45‘, ‘3:01‘, ‘2:01‘, ‘2:01‘, ‘3:10‘, ‘2:22‘]>>> jamesLee = [t.replace(‘:‘,‘-‘) for t in james]>>> jamesLee[‘2-34‘, ‘3-21‘, ‘2-34‘, ‘2-45‘, ‘3-01‘, ‘2-01‘, ‘2-01‘, ‘3-10‘, ‘2-22‘]
Sort
- Sort () provides in-place ordering without saving the original order
- Sorted () Copy sort, return a sorted copy
- The default sort method is ascending, descending reverse=true parameter
Using collections to remove list duplicates
>>> james[‘2:01‘, ‘2:01‘, ‘2:22‘, ‘2:34‘, ‘2:34‘, ‘2:45‘, ‘3:01‘, ‘3:10‘, ‘3:21‘]>>> unique = set(james)>>> uniqueset([‘2:45‘, ‘3:21‘, ‘2:01‘, ‘2:22‘, ‘2:34‘, ‘3:10‘, ‘3:01‘])>>> james = list(unique)>>> james[‘2:45‘, ‘3:21‘, ‘2:01‘, ‘2:22‘, ‘2:34‘, ‘3:10‘, ‘3:01‘]
Head_first_python Study Notes (iii)