Skip to content

Python Close() File | Function

  • by

Python Close() File Function is used to close an open file. Once the file is closed file can’t be read or written anymore.

It’s a good practice to close files, in some cases, due to buffering, changes made to a file may not show until you close the file.

fileObject.close()

Note: Python automatically closes a file when the reference object of a file is reassigned to another file.

Python Close File Function

Simple example code Close a file after it has been opened.

# Open a file
fo = open("foo.txt", "wb")
print("Name of the file: ", fo.name)

# Close opend file
fo.close()

Output:

Python Close File Function

Do comment if you have any doubts or suggestions on this Python file topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *