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

It’s considered good practice to use the with statement in Python when dealing with file I/O, as it automatically closes the file for you once the block of code is exited, even if an exception is raised within the block:

Alternatively, you can use the with statement, which automatically closes the file for you when you’re done working with it:

# Open a file using with statement
with open("example.txt", "w") as file:
    # Write some data to the file
    file.write("Hello, world!")

# File is automatically closed when exiting the 'with' block

Using the with statement is generally considered more Pythonic and safer because it ensures that the file is properly closed even if an exception occurs within the block.

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 *