import functools def my_sort(): his_file = ['bba1', 'bba1.1', 'bba2', 'bba2.1', 'bba3', 'bba4'] def cmp(file1, file2): if file1[:4] != file2[:4]: # only return -1, 0, 1 return 1 if file1[:4] < file2[:4] else -1 else: return 1 if file1[4:] > file2[4:] else -1 his_file = sorted(his_file, key=functools.cmp_to_key(cmp)) print(his_file) his_file = his_file[5:] if len(his_file) < 1: return print('Delete history logfile %s', ','.join(his_file)) for file_name in his_file: print(file_name)