#demo0701.py
import os
try:
file1 = open(“dat”,“w”) #打开当前目录下的文本文件dat以便写入,file1为文件对象
#实际上dat也可以换成完整的路径+文件名
file1.write(“10000”) #写入字符串10000
except FileNotFoundError: #文件读写操作可能发生异常,这里捕获三种异常,文件不存在、
#没有足够操作权限和其它异常
print("File not found error\n")
except PermissionError:
print("Permission error\n")
except BaseException:
print("Other unexpected error")
finally:
file1.close() #不论文件操作正确与否,都必须关闭文件
复制代码