Python

How to check a file is opened or closed in Python

The file is used to store data permanently. Working with a file is a very common task of any programming language. Many built-in functions exist in Python to create, open, read, write and close the file. Two types of files can be created to store data. These are text files and binary files. Any file is required to open before reading or write. The open() function is used in Python to open a file. Using the open() function is one way to check a particular file is opened or closed. If the open() function opens a previously opened file, then an IOError will be generated. Another way to check a file is opened or closed is to check the values of the closed property of the file handler object. Using rename() function is another way to check the file is opened or closed. Different ways to check any file is opened or closed in Python have been shown in this tutorial.

Create a file for checking:

You can use any existing file or create a new file to test the example code shown in this tutorial. A new text file named clients.txt has been created with the following content to use later in the next part of the tutorial.

ID     Name                       Email
01     Jony Liver                [email protected]
02     Manik Hossain        [email protected]
03     Neha Akter              [email protected]
04     Janatul Ferdous      [email protected]
05     Helal Uddin             [email protected]

Example-1: Check the file is opened or not by using IOError

IOError generates when the open() function is called to open a file that has been opened before. Create a python file with the following script to check a file is opened or not by using try-except block. Here, any existing filename will be taken as input and opened for reading. Next, the open() function is called again to open the same file that will raise an IOError and print the error message.

# Take the filename to check
filename = input("Enter any existing filename:\n")
# Open the file for the first time using open() function
fileHandler = open(filename, "r")
# Try to open the file same file again
try:
    with open("filename", "r") as file:
        # Print the success message
        print("File has opened for reading.")
# Raise error if the file is opened before
except IOError:
    print("File has opened already.")

Output:

The following output will appear after executing the above script. Here, clients.txt exists in the current location, and the error message, “File has opened already,” has printed for the IOError exception.

Example-2: Check the file is closed or not by using the closed property.

The value of the closed property will be true if any file is closed. Create a python file with the following script to check a file is closed or not that exists in the current location. The previous example script will generate an error if the filename taken from the user does not exist in the current location. This problem has solved in this example. The os module is used here to check the existence of the filename that will be taken from the user. The check_closed() function has defined to check the file is closed or not that will be called if the file exists.

# Import os module to check the existence of the file
import os
# Drfine function check the file is closed or not
def check_closed():
    if fileHandler.closed == False:
        # Print the success message
        print("File has opened for reading.")
    else:
        # Print the error message
        print("File has closed.")

# Take the filename to check
filename = input("Enter any existing filename:\n")
# Check the file exist or not
if os.path.exists(filename):
    # Open the file for reading
    fileHandler = open(filename, "r")
    # Call the function
    check_closed()
else:
    # Print message if the file does not exist
    print("File does not exist.")

Output:

The following output will appear after executing the above script. Here, clients.txt exists in the current location, and the success message, “File has opened for reading,” has printed because the value of the closed property returned False.

Example-3: Check the file is opened or not by using OSError

The OSError generates when the rename() function is called more than one time for a file that is opened already. Create a python file with the following script to check a file is opened or closed by using OSError. The os module has been used in the script to check the file’s existence and rename the file. When the rename() function is called for the second time, OSError will be generated, and the custom error message will be printed.

# Import os module to check the existence of the file
import os
# Set the existing filename
filename = 'clients.txt'
# Set the new filename
newname = 'customers.txt'
# Check the file exist or not
if os.path.exists(filename):
    try:
        # Call the rename function for the first time
        os.rename(filename, newname)
        # Call the rename function for the second time
        os.rename(filename, newname)
    # Raise error if the file has opened
    except OSError:
        print("File is still opened.")

else:
    # Print message if the file does not exist
    print("File does not exist.")

Output:

The following output will appear after executing the above script. Here, clients.txt exists in the current location, and the error message, “File is still opened,” has printed because the OSError exception has generated when the second rename() function has been executed.

Conclusion:

When we need to work with the same file multiple times in a script, it is essential to know whether the file is opened or closed. It is better to call the close() function to close the file after completing the file operation. The error occurs when a file is opened for the second time in the same script without closing it. Different solutions to this problem have been shown in this tutorial by using simple examples to help the python users.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.