一、With...as...概述:
- with语句 是用来简化代码的
- 在将打开文件的操作放在 with 语句中,代码块结束后,文件将自动关闭资源,不用在书写close()语句
- 读写文件的逻辑没有变化,变得只是写法
二、用法示例
- with...as...读
# with....as.....文件读写的简写方式
# 会自动关闭资源
with open("/etc/hostname", mode="r") as fr1:
print(fr1.read())
- with...as...写
# with....as.....文件写入文件内容
with open("/opt/test.txt", mode="w") as fw1:
fw1.write("hello world!\n")
网友评论