python -- 基础知识测试

来源:互联网 发布:知乎校园招聘2017 编辑:程序博客网 时间:2024/06/06 11:35
#! /usr/bin/python3print("------read file first method------")tf = open('sketch.txt');for echo_line in tf:if  echo_line.find(':') >= 0:(role, line_spoken) = echo_line.split(':', 1);print(role, end='');print(' said: ', end='');print(line_spoken, end='');tf.close();print("------read file second method------")man = [];other = [];try:tf = open('sketch.txt');for echo_line in tf:try:(role, line_spoken) = echo_line.split(':', 1);line_spoken = line_spoken.strip();if role == 'Man' :man.append(line_spoken);elif role == 'Other Man' :other.append(line_spoken);except ValueError:passtf.close();print(man)print(other)except IOError:print('The file is missing.');print("------read file third method------")man = [];other = [];try:tf = open('sketch.txt');for echo_line in tf:try:(role, line_spoken) = echo_line.split(':', 1);line_spoken = line_spoken.strip();if role == 'Man' :man.append(line_spoken);elif role == 'Other Man' :other.append(line_spoken);except ValueError:passexcept IOError as err:print('The file is missing.' + str(err));finally:if 'tf' in locals():tf.close();try:out_man = open('man_data.out', "w");out_other = open('other_data.out', "w");print(man, file=out_man)print(other, file=out_other)out_man.close();out_other.close();except IOError as err:print('File error' + str(err));finally:if 'out_man' in locals():out_man.close();if 'out_other' in locals():out_other.close();print("------read file fourth method------")man = [];other = [];try:with open('sketch1.txt') as tf:for echo_line in tf:try:(role, line_spoken) = echo_line.split(':', 1);line_spoken = line_spoken.strip();if role == 'Man' :man.append(line_spoken);elif role == 'Other Man' :other.append(line_spoken);except ValueError:passprint(man)print(other)except IOError as err:print('The file is missing.' + str(err));print("------read file test use module:pickle ------")import pickle;man = ['I', 'Love', 'U'];try:with open('sketch.pickle', 'wb') as tf:#pickle.dump(man, tf);pickle.dump(['We', 'will', 'rock', 'you'], tf);with open('sketch.pickle', 'rb') as tf_r:other = pickle.load(tf_r);print(other)except pickle.PickleError as perr:print('The file is missing.' + str(perr));


原创粉丝点击