您的位置:首页 > 编程语言 > Python开发

python -- 基础知识测试

2017-11-29 11:18 253 查看
#! /usr/bin/python3

print("------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:
pass
tf.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:
pass
except 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:
pass
print(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));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: