Python try/except/finally应用

1.通过if和else处理异常

import os
if os.path.exists('sketch.txt'):
    data = open ('sketch.txt')

    for each_line in data:
        if not each_line.find(':') == -1:
            (role, line_spoken) = each_line.split(':',1)
            print (role, end ='')
            print (' said ',end = '')
            print   (line_spoken, end ='')
    data.close()
else:
    print("The datafile is missing")
    

2.通过try/except处理异常

try:
    data = open('sketch.txt')

    for each_line in data:
        try:
            (role,line_spoken) = each_line.split(':',1)
            print(role,end='     ')
            print('saiding=>',end='')
            print(line_spoken,end='')
        except ValueError:
            pass
    data.close()
except IOError:
    print('The datafile is missing2!')
    

2.通过try/except/finally处理异常

try:
    man_file = open('man_data.txt','w')
    other_file = open('other_data.txt','w')

    print('hello man', file=man_file)
    print('hello other', file=other_file)
except IOError:
    print('File error.')
finally:
    man_file.close()
    other_file.close()
原文地址:https://www.cnblogs.com/oskb/p/4835128.html