How to check whether file is open or not

Mattias Nilsson mattias at
Wed Mar 7 10:47:30 CET 2007

Ros wrote:
> There are 10 files in the folder. I wish to process all the files one
> by one. But if the files are open or some processing is going on them
> then I do not want to disturb that process. In that case I would
> ignore processing that particular file and move to next file.
> How can I check whether the file is open or not?

 From what I know: You can't, in a platform independent way.

You'd still be in trouble even if python would let you write something like:

if file_is_open(filename):

There's nothing that says no one will open the file after the 
file_is_open call but before the process_file call. Also, the file might 
be opened during the processing.

If the files to be processed only are written and then closed without 
being reopened or modified, then your situation is a bit simpler.

If you can get the process that creates the files to cooperate, a common 
way to solve this problem is to have a temporary suffix on files while 
they are being created. Once the file is complete, the temporary suffix 
is removed and that signals to other processes that this file is ready 
for processing.

More information about the Python-list mailing list