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.
Python File close() Method The close() method closes an open file. You should always close your files, in some cases, due to buffering, changes made to a file may not show until you close the file.
In Python, you can check whether certain files or directories exist using the isfile() and isdir() methods, respectively. However, if you use isfile() to check if a certain directory exists, the method will return False. Likewise, if you use if isdir() to check whether a certain file exists, the method returns False.
Python has a close() method to close a file. The close() method can be called more than once and if any operation is performed on a closed file it raises a ValueError. The below code shows a simple use of close() method to close an opened file.
Check to make sure the file was successfully opened by checking to see if the variable == NULL. If it does, an error has occured. Use the fprintf or fscanf functions to write/read from the file. Usually these function calls are placed in a loop.
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 :) )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With