Python File close() 方法关闭当前打开的文件。众所周知,如果打开文件以对其执行任务,则必须在任务完成后关闭该文件。这是为了确保操作系统上打开的文件量不超过它设置的限制。
在操作系统中关闭文件是必要的,因为打开的文件过多容易出现漏洞并可能导致数据丢失。因此,除了此方法之外,当文件的引用对象被重新分配给另一个文件时,Python 会自动关闭一个文件。但是,仍然建议使用 close() 方法以适当的方式关闭文件。
文件关闭后,将无法再读取或写入该文件。如果对已关闭的文件执行操作,则会引发 ValueError,因为必须打开该文件才能执行操作。
注意:此方法可以在程序中多次调用。
语法
以下是 Python close() 方法的语法 -
fileObject.close()
参数
该方法不接受任何参数。
返回值
此方法不返回任何值。
示例1
以下示例显示了 Python close() 方法的用法。首先,我们使用文件对象 “fo” 打开一个文件,该对象具有写入二进制 (wb) 模式。然后,我们在使用 close() 方法关闭它之前显示文件名。
# Open a file using a file object 'fo'
fo = open("foo.txt", "wb")
print("Name of the file: ", fo.name)
# Close the opened file
fo.close()
当我们运行上述程序时,它会产生以下结果——
Name of the file: foo.txt
示例2
文件关闭后,我们无法对文件执行任何操作。这将引发 ValueError。
在这里,使用文件对象以写入模式 (w) 打开测试文件 “foo.txt”。然后,使用 close() 方法,我们在尝试对它执行写入操作之前关闭此文件。
# Open a file using a file object 'fo'
fo = open("foo.txt", "w")
# Close the opened file
fo.close()
# Perform an operation after closing the file
fo.write("Hello")
让我们编译并运行给定的程序,以产生以下输出 -
Traceback (most recent call last):
File "main.py", line 8, in <module>
fo.write("Hello")
ValueError: I/O operation on closed file.
File "main.py", line 8, in <module>
fo.write("Hello")
ValueError: I/O operation on closed file.
示例3
close() 方法可以在单个程序中多次调用。
在以下示例中,我们将在写入 (w) 模式下打开一个名为“test.txt”的文件。然后,在调用 close() 方法两次之前,对文件执行写入操作。
# Open a file using a file object 'fo'
fo = open("test.txt", "w")
# Perform an operation after closing the file
fo.write("Hello")
# Close the opened file
fo.close()
fo.close()
一旦我们执行了上面的程序,使用 write() 方法编写的字符串将反映在 test.txt 文件中,如下所示。
Hello