Python 之 基本的异常处理
# 基本的异常处理 之 try-except-finally:
data = '0123456789abcdefg' # 要写入文件的数据
try:
one_file = open("first.txt", 'w') # 打开 first.txt 文件
two_file = open("second.txt", 'w') # 打开 second.txt 文件
print(data, file=one_file) # 写入 first.txt文件
print(data, file=two_file) # 写入 second.txt文件
except IOError as err:
print('File error: ' + str(err)) # 异常处理
finally:
if 'one_file' in locals(): # 判断文件是否被打开
one_file.close()
if 'two_file' in locals():
two_file.close()
#'''
# 基本的异常处理 之 with-as:
data = '0123456789abcdefg'
with open('first.txt', 'w') as one_file, open('second.txt', 'w') as two_file:
print(data, file=one_file)
print(data, file=two_file)
#'''
浙公网安备 33010602011771号