Luan Pham
Luan Pham

Reputation: 599

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

How can I check the file "file_name" is still open or not with this command?

csv_gen = (row for row in open(file_name))

I know we should use something like

with open(file_name) as file_name_ref:
    csv_gen = (row for row in file_name_ref)

but what's happened and how can I check the behavior if I use the former command.

Upvotes: 6

Views: 582

Answers (2)

chepner
chepner

Reputation: 532278

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 :) )

Upvotes: 3

DYZ
DYZ

Reputation: 57105

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.

Upvotes: 7

Related Questions