[Tutor] how to check if a file is being used by another person or application before writing to it?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Nov 30 22:42:17 CET 2004

On Tue, 30 Nov 2004, Jeff Peery wrote:

> I need to read/write from/to a file although I do not want to read/write
> a file that is being used by another person or application.

Hi Jeff,

The concept of a file "lock" should do the trick.  See:


The idea is to have one person "lock" the file when they open it.  This
prevents other people from opening the same file, as long as they check
the lock first.  The caveat is that this kind of locking has to be done
intentionally: if one person forgets to check the lock, the whole scheme
falls apart.

> is there a way to check if a file is already open by another person?
> this way I could use some sort of clock to periodically check if a
> specific file is open and when it isn't open then I could do what I need
> to it.

> similarly is there a way to check if a file has been written to?

One alternative is to make some kind of 'signature' of a file.  This
signature can be a function of the file's content.  Take a signature at
one time point, and another at a later time, and if the signatures don't
match, the file was definitely munged.  The 'md5' module might be useful
for generating these file signatures:


> I suppose I would do something like periodically check the size of a
> particular file and if it increased then I would know it was written to.
> I didn't see anything in the python documentation for geting the size of
> a file.

The 'os.stat()' function should do the trick:


For example, on my Linux system, my /etc/passwd file is 1919 bytes:

[dyoo at shoebox dyoo]$ ls -l /etc/passwd
-rw-r--r--  1 root root 1919 Oct 22 16:51 /etc/passwd

and we get the same number from os.stat() in Python:

>>> os.stat('/etc/passwd').st_size

Hope this helps!

More information about the Tutor mailing list