Gice

Technology and General Blog

The file is utilized to store facts forever. Performing with a file is a extremely frequent endeavor of any programming language. A lot of designed-in functions exist in Python to make, open, examine, compose and close the file. Two kinds of data files can be created to retailer info. These are text information and binary files. Any file is expected to open up before looking at or write. The open up() purpose is applied in Python to open up a file. Applying the open up() purpose is a single way to verify a distinct file is opened or closed. If the open() operate opens a earlier opened file, then an IOError will be created. A different way to examine a file is opened or closed is to check out the values of the shut residence of the file handler item. Employing rename() operate is a further way to check out the file is opened or closed. Different strategies to examine any file is opened or closed in Python have been shown in this tutorial.

Build a file for checking:

You can use any current file or build a new file to test the instance code demonstrated in this tutorial. A new text file named clientele.txt has been designed with the pursuing information to use later on in the up coming 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: Verify the file is opened or not by utilizing IOError

IOError generates when the open up() functionality is referred to as to open a file that has been opened in advance of. Generate a python file with the adhering to script to check a file is opened or not by employing test-except block. Right here, any present filename will be taken as enter and opened for reading. Following, the open up() perform is named once more to open the very same file that will increase an IOError and print the mistake message.

# Choose the filename to look at
filename = input(“Enter any current filename:n)
# Open up the file for the 1st time utilizing open up() perform
fileHandler = open up(filename, “r”)
# Try out to open the file exact same file once again
consider:
    with open up(“filename”, “r”) as file:
        # Print the achievement message
        print(“File has opened for looking through.”)
# Elevate mistake if the file is opened in advance of
besides IOError:
    print(“File has opened by now.”)

Output:

The pursuing output will surface following executing the above script. In this article, consumers.txt exists in the present-day spot, and the error information, “File has opened by now,” has printed for the IOError exception.

Example-2: Look at the file is shut or not by utilizing the closed house.

The benefit of the shut home will be correct if any file is closed. Produce a python file with the adhering to script to check a file is closed or not that exists in the current location. The former instance script will create an error if the filename taken from the person does not exist in the present-day site. This issue has solved in this case in point. The os module is applied in this article to check the existence of the filename that will be taken from the person. The check_shut() perform has described to examine the file is shut or not that will be identified as if the file exists.

# Import os module to check out the existence of the file
import os
# Drfine perform check the file is shut or not
def verify_shut():
    if fileHandler.shut == False:
        # Print the good results message
        print(“File has opened for reading through.”)
    else:
        # Print the error information
        print(“File has closed.”)

# Take the filename to check out
filename = enter(“Enter any present filename:n)
# Look at the file exist or not
if os.route.exists(filename):
    # Open up the file for studying
    fileHandler = open up(filename, “r”)
    # Call the functionality
    verify_shut()
else:
    # Print concept if the file does not exist
    print(“File does not exist.”)

Output:

The adhering to output will seem following executing the previously mentioned script. Listed here, purchasers.txt exists in the existing spot, and the achievement information, “File has opened for looking through,” has printed mainly because the worth of the shut assets returned Fake.

Instance-3: Verify the file is opened or not by making use of OSError

The OSError generates when the rename() purpose is identified as additional than 1 time for a file that is opened previously. Create a python file with the following script to check a file is opened or closed by applying OSError. The os module has been employed in the script to check the file’s existence and rename the file. When the rename() function is known as for the 2nd time, OSError will be generated, and the tailor made mistake information will be printed.

# Import os module to test the existence of the file
import os
# Set the present filename
filename = ‘clients.txt’
# Set the new filename
newname = ‘customers.txt’
# Look at the file exist or not
if os.path.exists(filename):
    try:
        # Simply call the rename function for the to start with time
        os.rename(filename, newname)
        # Call the rename operate for the second time
        os.rename(filename, newname)
    # Elevate mistake if the file has opened
    other than OSError:
        print(“File is however opened.”)

else:
    # Print information if the file does not exist
    print(“File does not exist.”)

Output:

The pursuing output will look immediately after executing the previously mentioned script. Below, shoppers.txt exists in the current location, and the error information, “File is continue to opened,” has printed since the OSError exception has produced when the next rename() function has been executed.

Summary:

When we will need to perform with the very same file multiple occasions in a script, it is necessary to know whether or not the file is opened or closed. It is better to connect with the near() functionality to shut the file following completing the file procedure. The mistake happens when a file is opened for the 2nd time in the exact same script without the need of closing it. Various answers to this dilemma have been demonstrated in this tutorial by using simple illustrations to help the python users.

Leave a Reply

Your email address will not be published. Required fields are marked *