[Tutor] how to check if a file is being used by another person
orapplication before writing to it?
alan.gauld at freenet.co.uk
Tue Nov 30 23:05:29 CET 2004
> 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
This is very dependant on the operating system.
For example CP/M used to tell you if a file was locked for
read or for write(one of CP/Ms few good features!), whereas
ISTR Unix only tells you its locked for writing - indeed
it may not lock the file at all for reads. I suspect
Microsoft will do the same but I've never tried...
One approach is to read the access time (see below) and
compare with now, but that's hardly an exact science!
> similarly is there a way to check if a file has been written to?
This is easier since both Unix and Windows provide access to
the modification time. This is better than checking size since
a modification could change two bytes say without changing the
Look in the os.stat() function docs and at the path.getmtime()
The stat() function also returns the access time which tells
you when the file was last read or executed. Unfortunately it
doesn't tell you if the file is still being accessed!
The usual approach in my experience is to open for write and
check for IOErrors. If no error then go ahead and write and
rely on the other program (if there is one) to either refuse
to update the file after a change or to warn the user (this
is what vi does).
Its not very satisfactory and I look forward to anyone else
providing a better answer on this one!
Author of the Learn to Program web tutor
More information about the Tutor