python怎么关闭文件_Python关闭文件

Python关闭文件教程 在 在 Python 中,打开文件使用 close函数详解 语法 fileObject.close(); 参数 参数 描述 file

Python关闭文件教程

在 Python 中,打开文件使用

close函数详解

语法

fileObject.close();

参数

参数

描述

fileObject

打开的文件对象。

说明

close 函数需要使用打开文件返回的文件对象来调用,close 函数不需要任何的

案例

close函数关闭文件

使用 close 函数打开关闭的文件

print("嗨客网(www.haicoder.net)")

file = open("C:/haicoder.txt")

print("before close fileName =", file.name)

print("before close fileClosed =", file.closed)

file.close()

print("after close fileName =", file.name)

print("after close fileClosed =", file.closed)

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

我们使用 open 函数的默认参数,即以只读模式打开文件 “C:/haicoder.txt”,此时,获取文件的关闭状态,返回了

即,我们使用文件对象的 close 函数,成功关闭了打开的文件。

多次关闭