Computer >> Computer tutorials >  >> Programming >> Python

How to close an opened file in Python?


To close an opened file in python, just call the close function on the file's object.

For example

>>> f = open('hello.txt', 'r')
>>> # Do stuff with file
>>> f.close()

Try not to open files in this way though as it is not safe. Use with ... open instead.

For example

with open('hello.txt', 'r') as f:
    print(f.read())

The file auto closes as soon as you escape the with block.