Python-文件

#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() #不论文件操作正确与否,都必须关闭文件
复制代码
全部评论

相关推荐

10-16 19:16
Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务