How can I check a file is closed or not in python?

You can get a list of all open files using platform-independent module psutil:

import psutil
open_files = [x.path for x in psutil.Process().open_files()]

If file_name is on the list, then it is open, possibly more than once.


One way is to dig into the generator object itself to find the reference to the TextIOWrapper instance returned by open; that instance has a closed attribute.

csv_gen.gi_frame.f_locals['.0'].closed

Once the generator is exhausted, gi_frame will become None, at which point whether the file is closed or not depends on whether the TextIOWrapper has been garbage-collected yet.

(This is a terrible way to do this, but I spent 10 minutes digging into the object, so wanted to share :) )

Tags:

Python

File