Python File close() Method



The Python File close() method closes the currently opened file. It is common knowledge that if a file is opened to perform a task on it, then it must be closed once the task is done. This is to make sure the amount of open files on an operating system do not exceed the limit it sets.

Closing a file is necessary in an operating system as leaving too many files open can be prone to vulnerabilities and might cause data loss. Therefore, apart from this method, Python automatically closes a file when the reference object of a file is reassigned to another file. However, it is still recommended to use the close() method to close a file in a proper way.

Once the file is closed, it cannot be read or written any more. If an operation is performed on a closed file, then a ValueError is raised as the file must be open for the action to be done.

Note: This method can be called multiple times in a program.

Syntax

Following is the syntax for the Python close() method −

fileObject.close()

Parameters

The method does not accept any parameters.

Return Value

This method does not return any value.

Example

The following example shows the usage of the Python close() method. Firstly, we open a file using a file object "fo" with the writing binary (wb) mode. Then, we are displaying the file name before closing it using the close() method.

# 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()

When we run above program, it produces following result −

Name of the file:  foo.txt

Example

We cannot perform any actions on the file once the file is closed. This will raise a ValueError.

Here, a test file "foo.txt" is opened in write mode (w) using a file object. Then, using the close() method, we close this file before trying to perform the write operation on it.

# 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")

Let us compile and run the program given, to produce the following output −

Traceback (most recent call last):
  File "main.py", line 8, in <module>
fo.write("Hello")
ValueError: I/O operation on closed file.

Example

The close() method can be called multiple times in a single program.

In the following example, we are opening a file named "test.txt" in the write (w) mode. Then, a write operation is performed on the file before calling the close() method twice.

# 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()

Once we execute the program above, the string written using the write() method is reflected in the test.txt file as shown below.

Hello
python_file_methods.htm
Advertisements