What does close() function do in Python?


The function close() closes an open file. For example: 

f = open('my_file', 'r+')
my_file_data = f.read()
f.close()

 The above code opens 'my_file'in read mode then stores the data it reads from my_file in my_file_data and closes the file. When you open a file, the operating system gives a file handle to read/write the file. You need to close it once you are done using the file. If your program encounters an error and doesn't call f.close(), you didn't release the file. To make sure it doesn't happen, you can use with open(...) as syntax as it automatically closes files regardless of whether an error was encountered:

 with open('my_file', 'r+') as f:
    my_file_data = f.read()

Updated on: 01-Oct-2019

238 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements