Python with as使用

Python with as教程

Python 中,使用 open 函数,打开 文件 对文件进行读写之后,一定要使用 close 关闭文件,否则会造成系统资源的浪费。

但是,如果我们在打开文件,或者是在操作文件的过程中,程序出现了异常,那么此时,我们就无法关闭文件,因此,在 Python 中,对应的解决方式是使用 with as 语句操作上下文管理器,它能够帮助我们自动分配并且释放资源。

使用 with as 操作已经打开的文件对象(本身就是上下文管理器),无论期间是否抛出异常,都能保证 with as 语句执行完毕后自动关闭已经打开的文件。

Python with as详解

语法

with 表达式 [as target]: 代码块

说明

其中,用 [] 括起来的部分可以使用,也可以省略。 target 参数 用于指定一个 变量,该语句会将 expression 指定的结果保存到该变量中。

Python with as操作文件详解

语法

with open(filename, file_mode) as f: pass

参数

参数 描述
filename 文件名。
file_mode 打开文件的模式。
f 打开成功后返回的文件对象。

说明

以 file_mode 的方式,打开 filename 文件,返回的文件指针为 f。此时,不再需要我们手动的进行关闭文件。

案例

使用with as读文件

使用 with as 进行读文件

print("嗨客网(www.haicoder.net)") with open("C:/haicoder.txt", "r") as f: fileContent = f.read() print("FileContent =", fileContent)

程序运行后,控制台输出如下:

49_Python with as操作文件.png

我们首先,使用 open 以只读模式打开文件,返回的文件指针为 f,接着,使用 f 调用 read 函数读取文件,并打印文件内容。

因为,我们这里使用的是 with as 操作文件,因此操作完毕之后,不需要手动关闭文件。

使用with as写文件

使用 with as 进行写文件

print("嗨客网(www.haicoder.net)") with open("C:/haicoder.txt", "w") as f: f.write("Study Python from haicoder") print("Write file success")

程序运行后,控制台输出如下:

50_Python with as读文件.png

我们首先,使用 open 以写模式打开文件,返回的文件指针为 f,接着,使用 f 调用 write 函数写文件。

使用with as读写文件

使用 with as 进行读写文件

print("嗨客网(www.haicoder.net)") with open("C:/haicoder.txt", "w+") as f: f.write("Hello HaiCoder Python") print("Write file success") f.seek(0) fileContent = f.read() print("FileContent =", fileContent)

程序运行后,控制台输出如下:

51_Python with as写文件.png

使用 with as 对文件进行读写,不需要手动关闭文件。

Python with as使用总结

使用 with as 操作已经打开的文件对象,无论期间是否抛出异常,都能保证 with as 语句执行完毕后自动关闭已经打开的文件。Python with as 语法:

with 表达式 [as target]: 代码块

Python with as 操作文件语法:

with open(filename, file_mode) as f: pass