- Python Built-in Functions
- Python All Built-in Functions
- Python print() Function
- Python input() Function
- Python int() Function
- Python float() Function
- Python len() Function
- Python range() Function
- Python str() Function
- Python ord() Function
- Python chr() Function
- Python ascii() Function
- Python pow() Function
- Python type() Function
- Python List Functions
- Python list() Function
- Python insert() Function
- Python append() Function
- Python extend() Function
- Python pop() Function
- Python remove() Function
- Python reverse() Function
- Python sort() Function
- Python sorted() Function
- Python Dictionary Functions
- Python dict() Function
- Python update() Function
- Python get() Function
- Python keys() Function
- Python setdefault() Function
- Python fromkeys() Function
- Python items() Function
- Python popitem() Function
- Python Tuple Function
- Python tuple() Function
- Python Set Functions
- Python set() Function
- Python frozenset() Function
- Python String Functions
- Python split() Function
- Python join() Function
- Python format() Function
- Python replace() Function
- Python Iterator Functions
- Python iter() Function
- Python min() Function
- Python max() Function
- Python sum() Function
- Python count() Function
- Python index() Function
- Python copy() Function
- Python clear() Function
- Python next() Function
- Python filter() Function
- Python enumerate() Function
- Python zip() Function
- Python reversed() Function
- Python Number Functions
- Python abs() Function
- Python bin() Function
- Python oct() Function
- Python hex() Function
- Python round() Function
- Python divmod() Function
- Python complex() Function
- Python File Handling Functions
- Python open() Function
- Python read() Function
- Python readable() Function
- Python readline() Function
- Python readlines() Function
- Python write() Function
- Python writable() Function
- Python writelines() Function
- Python close() Function
- Python seek() Function
- Python tell() Function
- Python flush() Function
- Python fileno() Function
- Python truncate() Function
- Python Class Functions
- Python object() Function
- Python property() Function
- Python getattr() Function
- Python setattr() Function
- Python hasattr() Function
- Python delattr() Function
- Python classmethod() Function
- Python staticmethod() Function
- Python issubclass() Function
- Python super() Function
- Python Misc Functions
- Python all() Function
- Python any() Function
- Python isatty() Function
- Python bool() Function
- Python callable() Function
- Python globals() Function
- Python locals() Function
- Python dir() Function
- Python id() Function
- Python isinstance() Function
- Python map() Function
- Python repr() Function
- Python slice() Function
- Python vars() Function
- Python Advance Functions
- Python help() Function
- Python hash() Function
- Python breakpoint() Function
- Python bytes() Function
- Python bytearray() Function
- Python memoryview() Function
- Python compile() Function
- Python eval() Function
- Python exec() Function
- Python Tutorial
- Python Tutorial
- Python Examples
- Python Examples
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:
close(fh)
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 fresherearth.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:
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("fresherearth.txt", "r") print(fh.read()) fh.close()
If you execute the above program, you'll see the following output produced by this program:
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("fresherearth.txt", "r") fh.close() print(fh.read())
Here is the output produced by this program:
See, the statement:
fh.read()
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() try: filehandle = open(filename, "r") print("\nContent of File is:") print(filehandle.read()) filehandle.close() print("\nEnter the New Content to Append: ", end="") content = input() filehandle = open(filename, "a+") filehandle.write("\n") filehandle.write(content) filehandle.seek(0) print("\nNow the Content of File is:") print(filehandle.read()) except FileNotFoundError as fnfe: print(fnfe) print("Creating the file...") filehandle = open(filename, "w+") print("The file \"", filename,"\" created!", sep="") print("\nEnter the Content to Write: ", end="") content = input() filehandle.write(content) filehandle.seek(0) print("\nThe Content of File is:") print(filehandle.read()) finally: filehandle.close()
Here is its sample run with user input fresherearth.txt as file name, I'm the new content. as content:
And here is another sample run with user input none.txt (a non-existing file), and I'm the content. as content:
In above program, the statement:
filehandle.write("\n")
is used to insert a newline before inserting or appending the new content. And the statement:
filehandle.seek(0)
is used to place the file pointer at beginning of the file. So that, all the content gets read.
« Previous Function Next Function »