How to close an opened file in Python?

ProgrammingPythonServer Side Programming

Open(), a built-in function in Python, opens a file and returns a file object. Methods and properties in file objects can be used to gather data about the file you opened. They may also be used to modify the mentioned file.

Open a file

Two arguments are required for this function. The filename and full path are listed first, followed by access mode. A file object is returned by this function.

syntax

Following is the syntax used to open a file:

open(filename, mode)

Here, the filename and it's path are specified by a string argument, and the mode argument is used to determine whether the file will be used for reading or writing.

Note − If the file and Python script are not in the same directory, you must specify the file's whole path. If you don't provide a mode, the access mode is read mode by default.

Example

Following is an example to open a file using r+ mode

# Opening a file file = open("file.txt", "r+") print ("Name of the file: ", file.name) print ("Opening mode : ", file.mode)

Output

Following is an output of the above code −

Name of the file: file.txt
Opening mode : r+ 

Various modes to open a file

  • ab  It opens the file in binary format, but otherwise is identical to a mode.
  • ab+  The file opens in binary format, but else is similar to a+ mode.
  • a+  Enables reading and adding to the file. If the file already exists, the file pointer is at the end of the file; otherwise, a new file is created for reading and writing.
  • − The file is opened for appending. The pointer is at the end of the file if it is present; otherwise, a new file is created for writing.
  • wb  /Similar as w mode, but opens the file in binary format.
  • wb+  The file is opened in binary format, unlike w+.
  • w+  Opens the file in read-only and write-only modes; rest is similar to w mode.
  •  Enables writing by opening the file. replaces the existing file and creates a new one if the existing file is absent.
  • rb − It opens the file in binary mode, but else is identical to r mode.
  • rb+  Similar to r+ mode, only opens the file in binary mode instead.
  • r+  Opens the file so that it can be read and written to. The file's starting point is where the pointer is.
  •  Read-only mode is used to open a file. The file's pointer is located at the start of the file. Additionally, this is the default mode.
  •  Opens for the exclusive creation of a file. The operation fails if the file already exists.
  •  Opens in text-only mode (default).
  •  A binary mode opening.
  •  updates a file by opening it (reading and writing).

Close a file

You can call close function using file object directly because it doesn't require any arguments. It may be called several times, but "ValueError" exception is raised if any operation is carried out on a closed file.

Example

Following is an example to close a file −

# Opening a file file = open("file.txt", "r+") # closing the file file.close()

Note − It is important to remember to always explicitly close each open file after its task is completed and there is no need to keep it open because a program can only open a certain amount of files at once. There is no safe way to recover if you go above that limit, thus the software might crash.

Close() is not completely secure. The function terminates without closing the file if an exception is thrown while we are trying to execute some operation on the file. Using a try...finally block is preferable.

Example

Following is an example explaining that even if an exception is generated and interrupts program execution, it is guaranteed that the file will be properly closed −

try: file = open("file.txt", "r+") finally: file.close()

Note − The safest approach to handle a file action in Python is to use the "with" statement because it makes sure that the file is closed when the block inside of it is exited.

Example

You don't have to explicitly call the close() method in the example below. The process is internal −

with open("file.txt", "r+") as file: # perform some file operations
raja
Updated on 17-Aug-2022 13:53:21

Advertisements