用open方法导入文件“sketch.txt”后,用split()方法进行分割:
>>> import os
>>> os.chdir('C:/Python33/HeadFirstPython/chapter3')
>>> data=open('sketch.txt')
>>> for each_line in data:
(role,spoken)=each_line.split(':',1) #使用split方法分割行数据
print(role,end='')
print('said: ',end='')
print(spoken,end='')
用with语句处理文件:
try:
with open('its.txt',"w") as data:
print ("It's...",file=data)
except IOError as err:
print ('File error:'+ str(err))