20190323——HeadFirestPython学习之异常处理
man=[] other=[] try: data=open('sketch.txt') for each_line in data: try: (role,line_spoken)=each_line.split(':',1) line_spoken=line_spoken.strip() if role=='A': man.append(line_spoken) elif role=='B': other.append(line_spoken) except ValueError: pass data.close() except IOError: print "the data file is missing" try: with open('man_data.txt',"w") as out: out.write(str(man)) except IOError: print "the second missing"
写入文件用WITH代替try except finally
try:
with open('man_data.txt',"w") as out:
out.write(str(man))
except IOError:
print "the second missing"
如果有二个文件可以用,隔开
with open('man_data.txt','w') as out, with open('other_data.txt','w') as out1:
out.write(str(man))
out.write(str(othe))
_______________________________________________
try:
out=open('man_data.txt',"w")
out.write(str(man))
except IOError as err:
print 'File error:'+str(err)
finally:
if 'data' in locals():
out.close()