Python - File detach() Method


Advertisements

The Python file detach() method is used to close the specified file. Please note that, file must has opened before using the method.

Syntax


file.detach()

Parameters

No parameter is required.

Example: Close an opened file in Python

In the below example, Python file close() method is used to close an opened file called MyFile. The file read() method before closing the file will return the content of the file and after closing the file will raise an exception.

MyFile = open("python_test.txt", "r")

#read content before closing the file
print(MyFile.read())
MyFile.close()

#read content after closing the file
print(MyFile.read())

Output

Python is a programming language.
Learning Python is fun.

ValueError: I/O operation on closed file.

Python File Handling Methods
Advertisements