How to close an opened file in Python?

PythonServer Side ProgrammingProgramming

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.

raja
Published on 22-Dec-2017 15:12:28
Advertisements