Python close() Function

The close() function in Python, used to close a file. That is, when a file is opened using open() function and all the operation has been done on the file, then the file object or handler must be closed using the close() function to break the linkage of file from the program.

Syntax of close() Function to Close a File

The syntax of close() function to close a file in Python is:


where fh indicates to the file handler or file object.

Python close() Function Example

Before proceeding the example given below, let's first create a file say codescracker.txt with some content. The file must be saved inside the current directory. Here is the snapshot of the current directory. That shows both, that is the file as well as its content:

Python close function

Now let's create a program, that uses this file to operate (read its content) and then close the file using close() function:

fh = open("codescracker.txt", "r")

If you execute the above program, you'll see the following output produced by this program:

close function python

Now the question may arise in your mind is, what if we again use the fh object, after closing it using close() function ?
Let's find out its answer, using the program given below:

fh = open("codescracker.txt", "r")

Here is the output produced by this program:

python close function example

See, the statement:

raises a ValueError after the file object fh being closed using close(). Let's create another program that shows, the efficient use of file handler, open() and close() function in Python:

print("Enter the Name of File: ", end="")
filename = input()
    filehandle = open(filename, "r")
    print("\nContent of File is:")
    print("\nEnter the New Content to Append: ", end="")
    content = input()
    filehandle = open(filename, "a+")
    print("\nNow the Content of File is:")
except FileNotFoundError as fnfe:
    print("Creating the file...")
    filehandle = open(filename, "w+")
    print("The file \"", filename,"\" created!", sep="")
    print("\nEnter the Content to Write: ", end="")
    content = input()
    print("\nThe Content of File is:")

Here is its sample run with user input codescracker.txt as file name, I'm the new content. as content:

python close function program

And here is another sample run with user input none.txt (a non-existing file), and I'm the content. as content:

close function in python

In above program, the statement:


is used to insert a newline before inserting or appending the new content. And the statement:

is used to place the file pointer at beginning of the file. So that, all the content gets read.

Python Online Test

« Previous Function Next Function »

Liked this post? Share it!