English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Basic Python Tutorial

Python Flow Control

Fonctions en Python

Types de données en Python

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Knowledge of Python

Python Reference Manual

Python file close() usage and example

Python File (File) Method

Overview

close() This method is used to close an opened file. After closing, the file can no longer be read or written. Otherwise, it will trigger ValueError Error. The close() method can be called multiple times.

When the file object is referenced to operate another file, Python will automatically close the previous file object. It is a good habit to close the file using the close() method.

Syntax

The syntax of the close() method is as follows:

fileObject.close();

Parameter

  • None

Return value

This method does not return any value.

Example

The following example demonstrates the use of the close() method:

# Open the file
fo = open("w3codebox.txt, "wb")
print("The file name is: ", fo.name)
# Close the file
fo.close()

The output result of the above example is:

The file name is:  w3codebox.txt

Python File (File) Method