Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

file

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.

like image 845
Luan Pham Avatar asked Apr 30 '20 18:04

Luan Pham


People also ask

What is file close () in Python?

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.

How do you check if a file is being used in Python?

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.

How do you read and close a file in Python?

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.

How can you check that whether a file is opened successfully or not explain?

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.


2 Answers

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.

like image 84
DYZ Avatar answered Oct 12 '22 11:10

DYZ


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

like image 22
chepner Avatar answered Oct 12 '22 11:10

chepner