Python

Python

Made by DeepSource

I/O operation on a closed file detected PTC-W0021

Bug risk
Major

The I/O operation is being performed on a resource that is closed. This will lead to a runtime error. It is recommended to perform I/O operation on files inside with blocks, as the file is automatically closed when the scope of with ends.

Bad practice

This is a very visible case of an I/O operation on a closed resource.

fp = open(resource_path, "w")
# do some operations on fp
fp.close()
# some code

fp.write("This will throw an error!")

Recommended

It is best to use a with statement context maneger here. Using with, you don't need to worry about closing the resource when you're done using it.

with open(resource_path, "w") as fp:
    # Do some operations on fp
    ...

References: